package com.lb.sssq.actions;

import java.io.Serializable;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.yunzhi.domain.RequestHeader;
import com.yunzhi.domain.ResultCode;
import com.yunzhi.domain.ResultConstant;
import com.yunzhi.domain.ResultDTO;
import com.yunzhi.util.RequestUtil;
import com.yunzhi.util.ResponseUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.edais.domain.IpLogBean;
import com.edais.domain.RiskEvaluation;
import com.edais.domain.User;
import com.edais.domain.UserInfo;
import com.edais.domain.UserLDActivityInfo;
import com.edais.domain.UserRecePayCard;
import com.edais.domain.UserVouchers;
import com.edais.domain.VouchersRule;
import com.edais.domain.WeixinMediaBinding;
import com.edais.log.IpLog;
import com.edais.service.ActivityService;
import com.edais.service.AssetsService;
import com.edais.service.CaptchaService;
import com.edais.service.CenterService;
import com.edais.service.EnjoyService;
import com.edais.service.JkxyService;
import com.edais.service.KcodeChannelService;
import com.edais.service.LoanService;
import com.edais.service.OrderService;
import com.edais.service.PointService;
import com.edais.service.RateRisesCouponsService;
import com.edais.service.RiskEvaluationService;
import com.edais.service.SMSService;
import com.edais.service.ShopVouchersService;
import com.edais.service.SystemSettingService;
import com.edais.service.UserCardService;
import com.edais.service.UserChannelPointService;
import com.edais.service.UserService;
import com.edais.service.UserVouchersService;
import com.edais.service.WeixinBindingService;
import com.edais.service.gift.GiftPackageOrderService;
import com.edais.util.DecimalFormatUtil;
import com.edais.util.MD5;
import com.edais.util.StringUtil;
import com.edais.util.weixinAbout.SendWeiXinUtil;
import com.edais.vo.OrderListVo;
import com.lb.sssq.domain.Scattered_sssq;
import com.lb.sssq.service.DepositService;
import com.lb.sssq.util.CommonUtil;
import com.lb.sssq.util.Consts;
import com.lb.sssq.util.Message;

import com.alibaba.fastjson.JSONObject;

@Controller
@RequestMapping("/deposit")
public class DepositAction implements Serializable{
	/**
	 * 
	 */
	private static final long serialVersionUID = -4830919067701566662L;

	private static final Log logger = LogFactory.getLog(DepositAction.class);

	@Autowired
	private DepositService depositService;
	@Autowired
	private CenterService centerService;
	@Autowired
	private UserService userService;
	@Autowired
	private AssetsService assetsService;
	@Autowired
	private UserCardService userCardService;
	@Autowired
	private PointService  pointService;
	
	/** 设置service */
	@Autowired
	private LoanService loanService;
	
	@Autowired
	private SMSService sMSService;
	@Autowired
	private RateRisesCouponsService rateRisesCouponsService;
	
	@Autowired
	private WeixinBindingService weixinBindingService;
	
	@Autowired
	private CaptchaService captchaService;
	
	@Autowired
	private OrderService orderService;
	
	@Autowired
	private ActivityService activityService;
	
	@Autowired
	UserChannelPointService userChannelPointService;
	
	@Autowired
	private UserVouchersService userVouchersService;
	
	@Autowired
	private EnjoyService enjoyService;
	
	@Autowired
	private JkxyService jkxyService;
	
	@Autowired
	private KcodeChannelService kcodeChannelService;
	
	@Autowired
	private SystemSettingService systemSettingService;
	
	@Autowired
	private ShopVouchersService shopVouchersService;
	
	@Autowired
	private GiftPackageOrderService giftPackageOrderService;
	
	@Autowired
	private RiskEvaluationService riskEvaluationService;
	
	/**
	 * 获取我的活期利率数据
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/findCurrentRate")
	public void findCurrentRate(HttpServletRequest request, HttpServletResponse response) {
		String result = "";
		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
		String userId = paramsMap.get("userId");
		try {
			Map<String, Object> resMap = depositService.findCurrentRate(userId);

			result = CommonUtil.setResultStringCn(resMap, 
					resMap.get("rescode").toString(), "", resMap.get("resmsg_cn").toString());

			CommonUtil.responseJson(result, response);
		} catch (Exception e) {
			logger.error("获取我的活期利率数据接口异常:" + com.edais.util.CommonUtil.printStackTraceToString(e));
			result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
				Consts.ERROR_CODE, "",
				Message.CnDescriptionExpression.BUSINESSE_ERROR);
			CommonUtil.responseJson(result, response);
		}
	}

	
	/**
	 * 余额宝详情接口
	 * 
	 * @param request
	 * @return response
	 * @throws Exception
	 */
	@RequestMapping(value = "/showIndex")
	public void showIndex(HttpServletRequest request, HttpServletResponse response){
		String result = "";
		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
		paramsMap.put("finaceId", "1");
		// 用户id
		String userId = paramsMap.get("userId");
		Map<String, Object> params = new HashMap<String, Object>();
		
		for(Map.Entry<String, String> entry : paramsMap.entrySet()){
			params.put(entry.getKey(), entry.getValue());
		}
		params.put("finaceId", "1");
		
		//活期当天投资人数
		String currentInvNum="0";
		try {
			String currentInvNumStr = loanService.currentInvestNum(new HashMap<String,Object>());
			if(currentInvNumStr!=null){
				JSONObject jsonObject = JSONObject.parseObject(currentInvNumStr);
				if(jsonObject!=null){
					currentInvNum=jsonObject.get("peoplenum")+"";
				}
			}
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		
		if (StringUtils.isBlank(userId)) {
			JSONObject json = new JSONObject();
			json.put("yesterdayGain", "0.00");    // 昨日收益
			json.put("currentIncome", "0.00");   // 在投收益
			json.put("accountAmount", "0.00");   // 在投金额
			json.put("incomeTotal", "0.00");   // 累计收益
			json.put("couponsRateRises", "0");   // 当然加息利率
			json.put("signInRateRises", "0");   // 签到加息
			
			json.put("peoplenum",currentInvNum);			//活期当天投资人数
			json.put("isCompleteTask", "0");	//用户是否完成任务
			
			try {
				Map<String, Object> mapResult = depositService.queryScatteredLoanInfo(params);
//				rtnJson.put("totalNum", mapResult.get("totalNum"));
//				rtnJson.put("investUserNum", mapResult.get("investUserNum"));
//				rtnJson.put("listSize", mapResult.get("listSize"));
				json.put("list", mapResult.get("list"));
				
				Map<String, Object> map = depositService.getExpectedRate(paramsMap.get("finaceId"));
				// 年化收益率
				json.put("annualizedReturnRate", map.get("annualizedReturnRate")); 
				// 调整利率
				json.put("adjustRate", "0");				
				
			} catch (Exception e) {
				logger.error("余额宝详情接口异常:" + com.edais.util.CommonUtil.printStackTraceToString(e));
				result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
					Consts.ERROR_CODE, "",
					Message.CnDescriptionExpression.BUSINESSE_ERROR);
				CommonUtil.responseJson(result, response);
				return;
			}
			json.put("rescode", Consts.SUCCESS_CODE);
			json.put("resmsg", "");
			json.put("resmsg_cn", "用户ID不能为空！");
			CommonUtil.responseJson(json.toString(), response);
			return;
		}
//		/** Redis获取信息 **/
//		result = RedisOperateUtil.getString(RedisContant.KEY_PRODUCT_CURRENT_DETAIL + userId);
		
		if (StringUtils.isNotBlank(result)) {
			CommonUtil.responseJson(result, response);
			return;
		}
		try {
			// 查询余额宝详情
			result = depositService.queryMoneyFundDetail(paramsMap);
			
			JSONObject rtnJson = new JSONObject();
			
			//合并 (/showInvestmentListInfo)获取活期标接口数据				
			Map<String, Object> mapResult = depositService.queryScatteredLoanInfo(params);
//			rtnJson.put("totalNum", mapResult.get("totalNum"));
//			rtnJson.put("investUserNum", mapResult.get("investUserNum"));
//			rtnJson.put("listSize", mapResult.get("listSize"));
			rtnJson.put("list", mapResult.get("list"));
			
			
			/**用户是否完成任务 （0：未完成	，1：已完成）*/
			JSONObject fundDetailObject = JSONObject.parseObject(result);
			//获取活期利率
			BigDecimal adjustRate=new BigDecimal(fundDetailObject.get("adjustRate").toString());
			//获取签到加息
			BigDecimal signInRateRises=new BigDecimal(fundDetailObject.get("signInRateRises").toString());
			//获取当日加息利率
			BigDecimal couponsRateRises=new BigDecimal(fundDetailObject.get("couponsRateRises").toString());
			//总加息
			BigDecimal totalRate=signInRateRises.add(couponsRateRises).add(adjustRate);
			//查询用户最高收益值上限
			float userMaxRaise=Float.valueOf(rateRisesCouponsService.findParamValueByName("user_max_raise"));
			String isCompleteTask="0";
			if(totalRate.floatValue()>=userMaxRaise){
				isCompleteTask="1";
			}
			rtnJson.put("isCompleteTask", isCompleteTask);
			
			rtnJson.put("peoplenum", currentInvNum);
			
			//两个JSON数据拼接
			result = result.substring(0, result.length() - 1);
									
			result += "," + rtnJson.toString().substring(1);
			
//			/** 数据跟新到redis **/
//			RedisOperateUtil.setString(RedisContant.KEY_PRODUCT_CURRENT_DETAIL + userId, result);
//			
			CommonUtil.responseJson(result, response);
		} catch (Exception e) {
			logger.error("余额宝详情接口异常:" + com.edais.util.CommonUtil.printStackTraceToString(e));
			result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
				Consts.ERROR_CODE, "",
				Message.CnDescriptionExpression.BUSINESSE_ERROR);
			CommonUtil.responseJson(result, response);
		}
	}
	
	/**
	 * 余额宝详情接口
	 * 
	 * @param request
	 * @return response
	 * @throws Exception
	 *//*
	@RequestMapping(value = "/showIndex")
	public void showIndex(HttpServletRequest request, HttpServletResponse response){
		String result = "";
		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
		paramsMap.put("finaceId", "1");
		// 用户id
		String userId = paramsMap.get("userId");
		if (StringUtils.isBlank(userId)) {
			JSONObject json = new JSONObject();
			json.put("yesterdayGain", "0.00");    // 昨日收益
			json.put("currentIncome", "0.00");   // 在投收益
			json.put("accountAmount", "0.00");   // 在投金额
			json.put("incomeTotal", "0.00");   // 累计收益
			json.put("couponsRateRises", "0");   // 当然加息利率

			try {
				Map<String, Object> map = depositService.getExpectedRate(paramsMap.get("finaceId"));
				// 年化收益率
				json.put("annualizedReturnRate", map.get("annualizedReturnRate")); 
				// 调整利率
				json.put("adjustRate", "0");
			} catch (Exception e) {
				logger.error("余额宝详情接口异常:" + com.edais.util.CommonUtil.printStackTraceToString(e));
				result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
					Consts.ERROR_CODE, "",
					Message.CnDescriptionExpression.BUSINESSE_ERROR);
				CommonUtil.responseJson(result, response);
				return;
			}
			json.put("rescode", Consts.SUCCESS_CODE);
			json.put("resmsg", "");
			json.put("resmsg_cn", "用户ID不能为空！");
			CommonUtil.responseJson(json.toString(), response);
			return;
		}
		*//** Redis获取信息 **//*
		result = RedisOperateUtil.getString(RedisContant.KEY_PRODUCT_CURRENT_DETAIL + userId);
		if (StringUtils.isNotBlank(result)) {
			CommonUtil.responseJson(result, response);
			return;
		}
		try {
			// 查询余额宝详情
			result = depositService.queryMoneyFundDetail(paramsMap);
			
			*//** 数据跟新到redis **//*
			RedisOperateUtil.setString(RedisContant.KEY_PRODUCT_CURRENT_DETAIL + userId, result);
			
			CommonUtil.responseJson(result, response);
		} catch (Exception e) {
			logger.error("余额宝详情接口异常:" + com.edais.util.CommonUtil.printStackTraceToString(e));
			result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
				Consts.ERROR_CODE, "",
				Message.CnDescriptionExpression.BUSINESSE_ERROR);
			CommonUtil.responseJson(result, response);
		}
	}*/
	
	/**
	 * 定期理财详情接口
	 * 
	 * @param request
	 * @return response
	 * @throws Exception
	 */
	@RequestMapping(value = "/showTermIndex")
	public void showTermIndex(HttpServletRequest request, HttpServletResponse response){

		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
		String result = "";
		
		// 用户id
		String userId = paramsMap.get("userId");
		if (StringUtils.isBlank(userId)) {
			JSONObject json = new JSONObject();
			json.put("totalAssets", 0);
			json.put("balanceMoney", 0);
			json.put("incomeAmount", 0);
			json.put("cashInMoney", 0);//冻结金额
			json.put("investmentAssets", 0);
			json.put("expectAmount", 0);
			json.put("rescode", Consts.SUCCESS_CODE);
			json.put("resmsg", Consts.SUCCESS_CN);
			json.put("resmsg_cn", "用户ID不能为空！");
			//组装参数
			Map<String, Object> params = new HashMap<String, Object>();
			for(Map.Entry<String, String> entry : paramsMap.entrySet()){
				params.put(entry.getKey(), entry.getValue());
			}
			
			try {
				//合并数据  [散标列表]/getLoanListInfo接口数据	
				Map<String, Object> rtnMap = loanService.queryScatteredLoanInfo(params);					
				json.put("totalNum", rtnMap.get("totalNum"));
				json.put("listSize", rtnMap.get("listSize"));			
				json.put("list", rtnMap.get("list"));
			} catch (Exception e) {
				logger.error("定期理财详情接口异常:" + com.edais.util.CommonUtil.printStackTraceToString(e));
				result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
					Consts.ERROR_CODE, "",
					Message.CnDescriptionExpression.BUSINESSE_ERROR);
				CommonUtil.responseJson(result, response);
			}
			CommonUtil.responseJson(json.toString(), response);
			return;
		}

		Map<String, Object> jsonMap = new HashMap<String, Object>();

//		/** Redis获取信息 **/
//		result = RedisOperateUtil.getString(RedisContant.KEY_PRODUCT_FIX_DETAIL + userId);
//		if (StringUtils.isNotBlank(result)) {
//			CommonUtil.responseJson(result, response);
//			return;
//		}

		try {
			jsonMap = this.assetsService.getAssetsTerm(userId, "108");                  //微信我的资产总览
			// 账户累计收益
			BigDecimal incomeAmount = BigDecimal.ZERO.setScale(2);
			incomeAmount = new BigDecimal(jsonMap.get("incomeAmount").toString()).setScale(2, BigDecimal.ROUND_DOWN);          //账户累计收益
			
			paramsMap.put("finaceId", "1");
			String fundDetailResult = depositService.queryMoneyFundDetail(paramsMap);  //app活期活期理财
			JSONObject fundDetailObject = JSONObject.parseObject(fundDetailResult);  
			// 活期累计收益
			BigDecimal currentIncomeAmount = BigDecimal.ZERO.setScale(2);
			currentIncomeAmount = new BigDecimal(fundDetailObject.getString("incomeTotal")).setScale(2, BigDecimal.ROUND_DOWN); 
			// 定期累计收益
			BigDecimal termIncomeAmount = BigDecimal.ZERO.setScale(2);
			termIncomeAmount = incomeAmount.subtract(termIncomeAmount);
			jsonMap.put("termIncomeAmount", termIncomeAmount);
			
			//组装参数
			Map<String, Object> params = new HashMap<String, Object>();
			
			for(Map.Entry<String, String> entry : paramsMap.entrySet()){
				
				params.put(entry.getKey(), entry.getValue());
			}
			
			//合并数据  [散标列表]/getLoanListInfo接口数据	
			Map<String, Object> rtnMap = loanService.queryScatteredLoanInfo(params);					
			JSONObject rtnJson = new JSONObject();			
			rtnJson.put("totalNum", rtnMap.get("totalNum"));
			rtnJson.put("listSize", rtnMap.get("listSize"));			
			rtnJson.put("list", rtnMap.get("list"));
						
			result = CommonUtil.setResultStringCn(jsonMap, jsonMap.get("rescode").toString(), jsonMap.get("resmsg").toString(),""); 
			
			//两个JSON数据拼接
			result = result.substring(0, result.length() - 1);			
			result += "," + rtnJson.toString().substring(1); 
			
//			
//			if (Consts.SUCCESS_CODE.equals(jsonMap.get("rescode"))) {
//				/** 数据更新到redis **/
//				RedisOperateUtil.setString(RedisContant.KEY_PRODUCT_FIX_DETAIL + userId, result);
//			}
			

			CommonUtil.responseJson(result, response);
		} catch (Exception e) {
			logger.error("定期理财详情接口异常:" + com.edais.util.CommonUtil.printStackTraceToString(e));
			result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
				Consts.ERROR_CODE, "",
				Message.CnDescriptionExpression.BUSINESSE_ERROR);
			CommonUtil.responseJson(result, response);
		}
	}
	
	/**
	 * 余额宝历史收益列表接口
	 * 
	 * @param request
	 * @return response
	 * @throws Exception
	 */
	@RequestMapping(value = "/historyProfit")
	public void historyProfit(HttpServletRequest request, HttpServletResponse response){
		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
		try {
			// 数据检查
			Map<String,Object> checkMap = historyProfitCheck(paramsMap);
			if (null == checkMap || !Consts.SUCCESS_CODE.equals(checkMap.get("code"))){
				String result = CommonUtil.setResultStringCn(
						new HashMap<String, Object>(), checkMap.get("code").toString(),
						"", checkMap.get("message").toString());
				// 处理返回结果
				CommonUtil.responseJson(result, response);
				return;
			}
			Map<String, Object> map = new HashMap<String,Object>();
			map.put("pageSize", checkMap.get("pageSize"));
			map.put("current", checkMap.get("current"));
			map.put("userId", paramsMap.get("userId"));
			map.put("finaceId", "1");
			
			// 查询余额宝历史收益列表
			String result = depositService.queryIncomeStatementList(map);
			CommonUtil.responseJson(result, response);
		} catch (Exception e) {
			logger.error("余额宝历史收益列表接口异常:" + com.edais.util.CommonUtil.printStackTraceToString(e));
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
				Consts.ERROR_CODE, "",
				Message.CnDescriptionExpression.BUSINESSE_ERROR);
			CommonUtil.responseJson(result, response);
		}
	}
	
	/**
	 * 查询上架表信息
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/showInvestmentList")
	public void showInvestmentList(HttpServletRequest request, HttpServletResponse response){
		long a=System.currentTimeMillis();
		Integer current = 1;
		Integer pageSize = 10;
		String planId="109";
		String sellingType="2";
		
		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
		String currentStr = paramsMap.get(Consts.Page.PAGE_CURRENT_NAME);   //当前页数
		String pageSizeStr = paramsMap.get(Consts.Page.PAGE_SIZE_NAME);     //页大小
		String sellingTypeTmp = paramsMap.get("sellingType");//上架类别
		String planIdTmp = paramsMap.get("planId");//计划id
		String userId = paramsMap.get("userId");
		String loanId = null;//标的id
		String loanIdTmp=paramsMap.get("loanId");
		try{
			if(currentStr != null && !("".equals(currentStr))){
				current = Integer.parseInt(currentStr);
			}
			if(pageSizeStr != null && !("".equals(pageSizeStr))){
				pageSize = Integer.parseInt(pageSizeStr);
			}
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("rowBegin",(current-1)*pageSize+1);
			map.put("rowEnd",current*pageSize);
			//上架类别
			if(null != sellingTypeTmp && !"".equals(sellingTypeTmp)){
				sellingType=sellingTypeTmp;
			}
			map.put("sellingType", sellingType);
			
			//计划id
			if(null != planIdTmp && !"".equals(planIdTmp)){
				planId=planIdTmp;
			}
			map.put("planId", planId);
			
			//上架时间
//			map.put("startSellingTime",CommonUtil.getDateYYYYMMDDHH24MMSS());
			//获取上架产品总数
			String totalNum = depositService.queryScatteredLoanCount(map);
			List<Scattered_sssq> scatteredList = depositService.queryScatteredLoan(map);
			
			
			/**
			 * 剩余金额小于起头金额，返回100%
			 * 当产品已经超过下架时间，返回100%
			 */
			/*for(Scattered sc:scatteredList){
				if(sc.getEndSaleTime()!=null){
					Date currentDate = new Date();
					if(currentDate.before(currentDate)){
						sc.setFinishedRatio(new BigDecimal(100));
					}
				}
				if(sc.getRemanAmount().compareTo(sc.getInvestMinAmount())==-1){
					sc.setFinishedRatio(new BigDecimal(100));
				}
			}*/
			List<Map<String,Object>> resultListMap = new ArrayList();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			/*for(Scattered sc:scatteredList){
				Map<String,Object> scMap = new HashMap<String,Object>();
				scMap.put("productName", sc.getProductName());
				scMap.put("annualRate", sc.getAnnualRate());
				scMap.put("remanAmount", sc.getRemanAmount());
				scMap.put("saleTotalAmount", sc.getSaleTotalAmount());
				scMap.put("endSaleTime", sc.getEndSaleTime()==null?"":sdf.format(sc.getEndSaleTime()));
				scMap.put("investMinAmount", sc.getInvestMinAmount());
				scMap.put("finishedRatio", sc.getFinishedRatio());
				scMap.put("id", sc.getId());
				resultListMap.add(scMap);
			}*/
			
			Map<String, Object> map2 = new HashMap<String, Object>();
			String investUserNum = "";
			//ouyy 优化
			StringBuffer bidIdBf=new StringBuffer();
			for(int i =0;i<scatteredList.size();i++){
				bidIdBf.append(String.valueOf(scatteredList.get(i).getBidId())+",");
			}
			String bidId=bidIdBf.toString();
			Map<String,Object> listEx=null;
			
			if(bidId.lastIndexOf(",")!=-1){
				bidId=bidId.substring(0,bidId.lastIndexOf(","));
				logger.debug("queryDepositLoanLenderDetailCountEx传值参数-------"+bidId);
				map2.put("bidId", bidId);
				listEx=loanService.queryDepositLoanLenderDetailCountEx(map2);
				logger.debug("queryDepositLoanLenderDetailCountEx返回结果-------"+listEx);
			}
			//获取活期利率
			Map<String, Object> resMap = depositService.findCurrentRate(userId);
			String adjustRate = resMap.get("adjustRate").toString();

			for(int i =0;i<scatteredList.size();i++){
				Scattered_sssq sc = scatteredList.get(i);
				Map<String,Object> scMap = new HashMap<String,Object>();
				scMap.put("productName", sc.getProductName());
				scMap.put("annualRate", sc.getAnnualRate());
				scMap.put("remanAmount", sc.getRemanAmount());
				scMap.put("saleTotalAmount", sc.getSaleTotalAmount());
				scMap.put("endSaleTime", sc.getEndSaleTime()==null?"":sdf.format(sc.getEndSaleTime()));
				scMap.put("investMinAmount", sc.getInvestMinAmount());
				scMap.put("finishedRatio", DecimalFormatUtil.getDecimalFormat0(BigDecimal.ONE.compareTo(sc.getFinishedRatio())>0 && BigDecimal.ZERO.compareTo(sc.getFinishedRatio())<0?BigDecimal.ONE:sc.getFinishedRatio()));
				scMap.put("id", sc.getId());
				scMap.put("loanId", sc.getBidId());
				//调整利率
				scMap.put("adjustRate", adjustRate);
				
				// 获取标的列表人数
				if(listEx!=null&&listEx.size()!=0&&listEx.size()==scatteredList.size()){
					if(listEx.containsKey(String.valueOf(sc.getBidId()))){
						scMap.put("investUserNum", listEx.get(String.valueOf(sc.getBidId())));
					}else{
						scMap.put("investUserNum", "1");
					}
				}else{
					map2.put("loanId", sc.getBidId());
					investUserNum = loanService.queryDepositLoanLenderDetailCount(map2);
					scMap.put("investUserNum", investUserNum);
				}
				//guanxuxing 返回时间  begin
				DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");	
				int day = 0;
				int hour = 0;
				int min = 0;
				int sec = 0;
				try {
					Date dateTime=sc.getStartSellingTime();   //产品上架时间
					logger.info("[上架时间]====>"+df.format(dateTime));
					logger.info("[当前时间]====>"+df.format(new Date(System.currentTimeMillis())));
					long time1 = System.currentTimeMillis();  //当前时间
					long time2 = dateTime.getTime();          //上架时间
					logger.info("[当前time1]-->"+time1);
					logger.info("[上架time2]-->"+time2);
					long diff=time2-time1;
					/*if (time1 < time2) {
						diff = time2 - time1;
					} else {
						diff = time1 - time2;
					}*/				
						day = (int) (diff / (24 * 60 * 60 * 1000));
						hour = (int) (diff / (60 * 60 * 1000) - day * 24);
						min = (int) ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60);
						sec = (int) (diff / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);	
						if(diff<0){
							day=0;  hour=0;  min=0; sec=0;
						}
					logger.info("[上架时间距离当前时间]-->" + day + "天" + hour + "小时" + min + "分"
							+ sec + "秒");
				} catch (Exception e) {
					logger.info("[获取时间发生异常]-->" + e.getMessage());
				}
				
				scMap.put("day", day);
				scMap.put("hour", hour);
				scMap.put("min", min);
				scMap.put("sec", sec);
				//guanxuxing 返回时间  end
				scMap.put("startSellingTime", sc.getStartSellingTime()==null?"":sdf.format(sc.getStartSellingTime()));
				
				resultListMap.add(scMap);
			}
			
			Map<String, Object> mapResult = new HashMap<String, Object>();
			mapResult.put("totalNum", totalNum);
//			mapResult.put("investUserNum", investUserNum);
			mapResult.put("listSize", String.valueOf(resultListMap.size()));
			mapResult.put("list", resultListMap);
			
			mapResult.put("resmsg_cn", "");
			String result = CommonUtil.setResultInfo(mapResult, Consts.SUCCESS_CODE, Consts.SUCCESS_DESCRIBE);
			// 处理返回结果
			CommonUtil.responseJson(result, response);
			
		}catch(Exception e){
			logger.debug("/deposit/showInvestmentList异常-----" + com.edais.util.CommonUtil.printStackTraceToString(e));
			
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
								Consts.ERROR_CODE, Consts.ErrorMsg.MSG00001,
								Message.CnDescriptionExpression.BUSINESSE_ERROR);
			// 处理返回结果
			CommonUtil.responseJson(result, response);
			return;
		}finally{
			System.out.println("deposit/showInvestmentList接口\t执行耗时："+(System.currentTimeMillis()-a)/1000f+"秒");
			logger.debug("deposit/showInvestmentList接口\t执行耗时："+(System.currentTimeMillis()-a)/1000f+"秒");
		}
		
	}
	
	
	/**
	 * 查询上架表信息(扩展 条件:根据(在售>预售>售罄 时间降序)获取1条上架活期标信息)
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/showInvestmentListInfo")
	public void showInvestmentListInfo(HttpServletRequest request, HttpServletResponse response){
		
		long a=System.currentTimeMillis();
			
		Integer current = 1;
		Integer pageSize = 10;
		String planId="109";
		String sellingType="2";
		
		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
		
		String currentStr = paramsMap.get(Consts.Page.PAGE_CURRENT_NAME);   //当前页数
		String pageSizeStr = paramsMap.get(Consts.Page.PAGE_SIZE_NAME);     //页大小
		String sellingTypeTmp = paramsMap.get("sellingType");//上架类别
		String planIdTmp = paramsMap.get("planId");//计划id
		String userId = paramsMap.get("userId");
		String loanId = null;//标的id
		String loanIdTmp=paramsMap.get("loanId");
		try{
			if(currentStr != null && !("".equals(currentStr))){
				current = Integer.parseInt(currentStr);
			}
			if(pageSizeStr != null && !("".equals(pageSizeStr))){
				pageSize = Integer.parseInt(pageSizeStr);
			}
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("rowBegin",(current-1)*pageSize+1);
			map.put("rowEnd",current*pageSize);
			//上架类别
			if(null != sellingTypeTmp && !"".equals(sellingTypeTmp)){
				sellingType=sellingTypeTmp;
			}
			map.put("sellingType", sellingType);
			
			//计划id
			if(null != planIdTmp && !"".equals(planIdTmp)){
				planId=planIdTmp;
			}
			map.put("planId", planId);
						
			
			Map<String, Object> mapResult = depositService.queryScatteredLoanInfo(map);
			
			

			String result = CommonUtil.setResultInfo(mapResult, Consts.SUCCESS_CODE, Consts.SUCCESS_DESCRIBE);
			// 处理返回结果
			CommonUtil.responseJson(result, response);
			
		}catch(Exception e){
			logger.debug("/deposit/showInvestmentListInfo异常-----" + com.edais.util.CommonUtil.printStackTraceToString(e));
			
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
								Consts.ERROR_CODE, Consts.ErrorMsg.MSG00001,
								Message.CnDescriptionExpression.BUSINESSE_ERROR);
			// 处理返回结果
			CommonUtil.responseJson(result, response);
			return;
		}finally{
			System.out.println("deposit/showInvestmentList接口\t执行耗时："+(System.currentTimeMillis()-a)/1000f+"秒");
			logger.debug("deposit/showInvestmentList接口\t执行耗时："+(System.currentTimeMillis()-a)/1000f+"秒");
		}		
	}	
	
//	/**
//	 * 查询上架表信息(扩展 条件:根据(在售>预售>售罄 时间降序)获取1条上架活期标信息)
//	 * @param request
//	 * @param response
//	 */
//	@RequestMapping(value = "/showInvestmentListInfo")
//	public void showInvestmentListInfo(HttpServletRequest request, HttpServletResponse response){
//		long a=System.currentTimeMillis();
//		Integer current = 1;
//		Integer pageSize = 10;
//		String planId="109";
//		String sellingType="2";
//		
//		// 解密请求参数
//		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
//		
//		String currentStr = paramsMap.get(Consts.Page.PAGE_CURRENT_NAME);   //当前页数
//		String pageSizeStr = paramsMap.get(Consts.Page.PAGE_SIZE_NAME);     //页大小
//		String sellingTypeTmp = paramsMap.get("sellingType");//上架类别
//		String planIdTmp = paramsMap.get("planId");//计划id
//		String userId = paramsMap.get("userId");
//		String loanId = null;//标的id
//		String loanIdTmp=paramsMap.get("loanId");
//		try{
//			if(currentStr != null && !("".equals(currentStr))){
//				current = Integer.parseInt(currentStr);
//			}
//			if(pageSizeStr != null && !("".equals(pageSizeStr))){
//				pageSize = Integer.parseInt(pageSizeStr);
//			}
//			Map<String, Object> map = new HashMap<String, Object>();
//			map.put("rowBegin",(current-1)*pageSize+1);
//			map.put("rowEnd",current*pageSize);
//			//上架类别
//			if(null != sellingTypeTmp && !"".equals(sellingTypeTmp)){
//				sellingType=sellingTypeTmp;
//			}
//			map.put("sellingType", sellingType);
//			
//			//计划id
//			if(null != planIdTmp && !"".equals(planIdTmp)){
//				planId=planIdTmp;
//			}
//			map.put("planId", planId);
//			
//			//上架时间
////			map.put("startSellingTime",CommonUtil.getDateYYYYMMDDHH24MMSS());
//			//获取上架产品总数
//			String totalNum = "1";
//			List<Scattered_sssq> scatteredList = depositService.queryScatteredLoanInfo(map);
//			
//			
//			/**
//			 * 剩余金额小于起头金额，返回100%
//			 * 当产品已经超过下架时间，返回100%
//			 */
//			/*for(Scattered sc:scatteredList){
//				if(sc.getEndSaleTime()!=null){
//					Date currentDate = new Date();
//					if(currentDate.before(currentDate)){
//						sc.setFinishedRatio(new BigDecimal(100));
//					}
//				}
//				if(sc.getRemanAmount().compareTo(sc.getInvestMinAmount())==-1){
//					sc.setFinishedRatio(new BigDecimal(100));
//				}
//			}*/
//			List<Map<String,Object>> resultListMap = new ArrayList();
//			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//			/*for(Scattered sc:scatteredList){
//				Map<String,Object> scMap = new HashMap<String,Object>();
//				scMap.put("productName", sc.getProductName());
//				scMap.put("annualRate", sc.getAnnualRate());
//				scMap.put("remanAmount", sc.getRemanAmount());
//				scMap.put("saleTotalAmount", sc.getSaleTotalAmount());
//				scMap.put("endSaleTime", sc.getEndSaleTime()==null?"":sdf.format(sc.getEndSaleTime()));
//				scMap.put("investMinAmount", sc.getInvestMinAmount());
//				scMap.put("finishedRatio", sc.getFinishedRatio());
//				scMap.put("id", sc.getId());
//				resultListMap.add(scMap);
//			}*/
//			
//			Map<String, Object> map2 = new HashMap<String, Object>();
//			String investUserNum = "";
//			//ouyy 优化
//			StringBuffer bidIdBf=new StringBuffer();
//			for(int i =0;i<scatteredList.size();i++){
//				bidIdBf.append(String.valueOf(scatteredList.get(i).getBidId())+",");
//			}
//			String bidId=bidIdBf.toString();
//			Map<String,Object> listEx=null;
//			
//			if(bidId.lastIndexOf(",")!=-1){
//				bidId=bidId.substring(0,bidId.lastIndexOf(","));
//				logger.debug("queryDepositLoanLenderDetailCountEx传值参数-------"+bidId);
//				map2.put("bidId", bidId);
//				listEx=loanService.queryDepositLoanLenderDetailCountEx(map2);
//				logger.debug("queryDepositLoanLenderDetailCountEx返回结果-------"+listEx);
//			}
//			//获取活期利率
//			Map<String, Object> resMap = depositService.findCurrentRate(userId);
//			String adjustRate = resMap.get("adjustRate").toString();
//
//			for(int i =0;i<scatteredList.size();i++){
//				Scattered_sssq sc = scatteredList.get(i);
//				Map<String,Object> scMap = new HashMap<String,Object>();
//				scMap.put("productName", sc.getProductName());
//				scMap.put("annualRate", sc.getAnnualRate());
//				scMap.put("remanAmount", sc.getRemanAmount());
//				scMap.put("saleTotalAmount", sc.getSaleTotalAmount());
//				scMap.put("endSaleTime", sc.getEndSaleTime()==null?"":sdf.format(sc.getEndSaleTime()));
//				scMap.put("investMinAmount", sc.getInvestMinAmount());
//				scMap.put("finishedRatio", DecimalFormatUtil.getDecimalFormat0(BigDecimal.ONE.compareTo(sc.getFinishedRatio())>0 && BigDecimal.ZERO.compareTo(sc.getFinishedRatio())<0?BigDecimal.ONE:sc.getFinishedRatio()));
//				scMap.put("id", sc.getId());
//				scMap.put("loanId", sc.getBidId());
//				//调整利率
//				scMap.put("adjustRate", adjustRate);
//				
//				// 获取标的列表人数
//				if(listEx!=null&&listEx.size()!=0&&listEx.size()==scatteredList.size()){
//					if(listEx.containsKey(String.valueOf(sc.getBidId()))){
//						scMap.put("investUserNum", listEx.get(String.valueOf(sc.getBidId())));
//					}else{
//						scMap.put("investUserNum", "1");
//					}
//				}else{
//					map2.put("loanId", sc.getBidId());
//					investUserNum = loanService.queryDepositLoanLenderDetailCount(map2);
//					scMap.put("investUserNum", investUserNum);
//				}
//				//guanxuxing 返回时间  begin
//				DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");	
//				int day = 0;
//				int hour = 0;
//				int min = 0;
//				int sec = 0;
//				try {
//					Date dateTime=sc.getStartSellingTime();   //产品上架时间
//					logger.info("[上架时间]====>"+df.format(dateTime));
//					logger.info("[当前时间]====>"+df.format(new Date(System.currentTimeMillis())));
//					long time1 = System.currentTimeMillis();  //当前时间
//					long time2 = dateTime.getTime();          //上架时间
//					logger.info("[当前time1]-->"+time1);
//					logger.info("[上架time2]-->"+time2);
//					long diff=time2-time1;
//					/*if (time1 < time2) {
//						diff = time2 - time1;
//					} else {
//						diff = time1 - time2;
//					}*/				
//						day = (int) (diff / (24 * 60 * 60 * 1000));
//						hour = (int) (diff / (60 * 60 * 1000) - day * 24);
//						min = (int) ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60);
//						sec = (int) (diff / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);	
//						if(diff<0){
//							day=0;  hour=0;  min=0; sec=0;
//						}
//					logger.info("[上架时间距离当前时间]-->" + day + "天" + hour + "小时" + min + "分"
//							+ sec + "秒");
//				} catch (Exception e) {
//					logger.info("[获取时间发生异常]-->" + e.getMessage());
//				}
//				
//				scMap.put("day", day);
//				scMap.put("hour", hour);
//				scMap.put("min", min);
//				scMap.put("sec", sec);
//				//guanxuxing 返回时间  end
//				scMap.put("startSellingTime", sc.getStartSellingTime()==null?"":sdf.format(sc.getStartSellingTime()));
//				
//				resultListMap.add(scMap);
//			}
//			
//			Map<String, Object> mapResult = new HashMap<String, Object>();
//			mapResult.put("totalNum", totalNum);
////			mapResult.put("investUserNum", investUserNum);
//			mapResult.put("listSize", String.valueOf(resultListMap.size()));
//			mapResult.put("list", resultListMap);
//			
//			mapResult.put("resmsg_cn", "");
//			String result = CommonUtil.setResultInfo(mapResult, Consts.SUCCESS_CODE, Consts.SUCCESS_DESCRIBE);
//			// 处理返回结果
//			CommonUtil.responseJson(result, response);
//			
//		}catch(Exception e){
//			logger.debug("/deposit/showInvestmentList异常-----" + com.edais.util.CommonUtil.printStackTraceToString(e));
//			
//			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
//								Consts.ERROR_CODE, Consts.ErrorMsg.MSG00001,
//								Message.CnDescriptionExpression.BUSINESSE_ERROR);
//			// 处理返回结果
//			CommonUtil.responseJson(result, response);
//			return;
//		}finally{
//			System.out.println("deposit/showInvestmentList接口\t执行耗时："+(System.currentTimeMillis()-a)/1000f+"秒");
//			logger.debug("deposit/showInvestmentList接口\t执行耗时："+(System.currentTimeMillis()-a)/1000f+"秒");
//		}
//		
//	}
	
	/**
	 * 厚钱宝详情接口数据检查
	 */
	private Map<String,Object> historyProfitCheck(Map<String,String> paramMap) throws Exception{
		Map<String,Object> resMap = new HashMap<String,Object>();
		
		String finaceId = paramMap.get("finaceId");
		String userId = paramMap.get("userId");
		String currentPageStr = paramMap.get(Consts.Page.PAGE_CURRENT_NAME);//当前页
		String pageSizeStr = paramMap.get(Consts.Page.PAGE_SIZE_NAME);//页大小
		Integer current = 1;
		Integer pageSize = 10;//默认显示10条
		
		if(StringUtils.isBlank(finaceId)){
			logger.error("厚钱宝历史收益列表接口数据检查失败：计划id为空" );
			resMap.put("code", Consts.ERROR_CODE);
			resMap.put("message", Message.CnDescriptionExpression.BUSINESSE_ERROR);
			return resMap;
		}
		
		if(StringUtils.isBlank(userId)){
			logger.error("厚钱宝历史收益列表接口数据检查失败：用户id为空" );
			resMap.put("code", Consts.ERROR_CODE);
			resMap.put("message", Message.CnDescriptionExpression.BUSINESSE_ERROR);
			return resMap;
		}
		
		//分页参数
		if (currentPageStr != null && !("".equals(currentPageStr))) {
			current = Integer.parseInt(currentPageStr);
		}
		if (pageSizeStr != null && !("".equals(pageSizeStr))) {
			pageSize = Integer.parseInt(pageSizeStr);
		}
		 
		resMap.put("pageSize", pageSize);
		resMap.put("current", current);
		resMap.put("code", Consts.SUCCESS_CODE);
		resMap.put("message", Consts.SUCCESS_DESCRIBE);
		return resMap;
	}
	
	/**
	 * 查询余额宝交易记录
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/getMoneyFundFlow")
	public void getMoneyFundFlow(HttpServletRequest request, HttpServletResponse response){
		Integer current = 1;
		Integer pageSize = 10;
		
		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
		String currentStr = paramsMap.get(Consts.Page.PAGE_CURRENT_NAME);   //当前页数
		String pageSizeStr = paramsMap.get(Consts.Page.PAGE_SIZE_NAME);     //页大小
		// 资金类型。 不传则全部  1 : 加入 2 : 转出
		String fundType = paramsMap.get("fundType");
		
		try{
			if(currentStr != null && !("".equals(currentStr))){
				current = Integer.parseInt(currentStr);
			}
			if(pageSizeStr != null && !("".equals(pageSizeStr))){
				pageSize = Integer.parseInt(pageSizeStr);
			}
			Map<String, String> map = new HashMap<String, String>();
			
			String userId = paramsMap.get("userId");

			if(StringUtils.isBlank(userId)){
				logger.error("查询余额宝交易记录数据检查失败：用户id为空" );
				String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
						Consts.ERROR_CODE, Consts.ErrorMsg.MSG00001,
						"userId不能为空！");
				// 处理返回结果
				CommonUtil.responseJson(result, response);
				return;
			}

			map.put("current",current.toString());
			map.put("pageSize",pageSize.toString());
			map.put("userId", userId);
			if (fundType != null && fundType.length() > 0) {
				map.put("fundType", fundType);
			} else {
				// 代表 加入和转出
				map.put("fundType", "0");
			}
			
			//调用核心查询历史记录
			String rtnMapString = depositService.queryMoneyFundFlow(map);
			
			// 处理返回结果
			CommonUtil.responseJson(rtnMapString, response);
		}catch(Exception e){
			logger.debug("/deposit/getMoneyFundFlow异常-----" + com.edais.util.CommonUtil.printStackTraceToString(e));
			
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
								Consts.ERROR_CODE, Consts.ErrorMsg.MSG00001,
								Message.CnDescriptionExpression.BUSINESSE_ERROR);
			// 处理返回结果
			CommonUtil.responseJson(result, response);
		}
		return;
	}
	/**
	 * 查询当前在投债权及借款人信息
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/getOrderCredit")
	public void getOrderCredit(HttpServletRequest request, HttpServletResponse response){
		Integer current = 1;
		Integer pageSize = 10;
		
		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
		String currentStr = paramsMap.get(Consts.Page.PAGE_CURRENT_NAME);   //当前页数
		String pageSizeStr = paramsMap.get(Consts.Page.PAGE_SIZE_NAME);     //页大小
		
		try{
			if(currentStr != null && !("".equals(currentStr))){
				current = Integer.parseInt(currentStr);
			}
			if(pageSizeStr != null && !("".equals(pageSizeStr))){
				pageSize = Integer.parseInt(pageSizeStr);
			}
			Map<String, String> map = new HashMap<String, String>();
			
			String orderId = paramsMap.get("userId");
			
			map.put("current",current.toString());
			map.put("pageSize",pageSize.toString());
			map.put("userId", orderId);
			
			//调用核心查询历史记录
			String rtnMapString = depositService.queryOrderCreditList(map);
			
			// 处理返回结果
			CommonUtil.responseJson(rtnMapString, response);
		}catch(Exception e){
			logger.debug("/deposit/getOrderCredit异常-----" + com.edais.util.CommonUtil.printStackTraceToString(e));
			
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
								Consts.ERROR_CODE, Consts.ErrorMsg.MSG00001,
								Message.CnDescriptionExpression.BUSINESSE_ERROR);
			// 处理返回结果
			CommonUtil.responseJson(result, response);
		}
		return;
	}
	
	/**
	 * 转出接口
	 * 
	 * @param request
	 * @return response
	 * @throws Exception
	 */
	@RequestMapping(value = "/trunOut")
	public void trunOut(HttpServletRequest request, HttpServletResponse response) {
		logger.info("======进入方法：deposit/trunOut=======");
		long a=System.currentTimeMillis();
		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
		paramsMap.put("finaceId", "1");

		try {
			// 数据检查
			Map<String,Object> checkMap = trunOutCheck(paramsMap);
			if (null == checkMap || !Consts.SUCCESS_CODE.equals(checkMap.get("code"))){
				String result = CommonUtil.setResultStringCn(
						new HashMap<String, Object>(), checkMap.get("code").toString(),
						"", checkMap.get("message").toString());
				// 处理返回结果
				CommonUtil.responseJson(result, response);
				return;
			}
			
			Map<String, Object> map = new HashMap<String,Object>();
			map.put("userId", paramsMap.get("userId"));
			map.put("finaceId", paramsMap.get("finaceId"));
			map.put("turnOutAmount", paramsMap.get("turnOutAmount"));
			map.put("payPwd", paramsMap.get("payPwd"));
			
			logger.info("======deposit/trunOut=======userId:"+paramsMap.get("userId"));

			// 转出接口
			String result = depositService.updateInvestmentAmount(map);
			//ouyy 活期赎回成功发送短信
			JSONObject jsonObject = JSONObject.parseObject(result);
			if(Consts.SUCCESS_CODE.equals(jsonObject.getString("rescode"))){
				
				/** 转出成功时清除有影响Redis数据 **/
				String userId = map.get("userId").toString();
//				RedisOperateUtil.deleteString(RedisContant.KEY_TRANSFER_RECORD_PAGE_TOTALSIZE + userId);
//				RedisOperateUtil.deleteObject(RedisContant.KEY_TRANSFER_RECORD_PAGE + userId);
//				RedisOperateUtil.deleteString(RedisContant.KEY_MY_ASSET_PAGE + userId);
//				RedisOperateUtil.deleteString(RedisContant.KEY_GET_FUND_FLOW_PAGE_TOTALNUM + userId);
//				RedisOperateUtil.deleteObject(RedisContant.KEY_GET_FUND_FLOW_PAGE + userId);
//				RedisOperateUtil.deleteString(RedisContant.KEY_PRODUCT_CURRENT_DETAIL + userId);
//				RedisOperateUtil.deleteString(RedisContant.KEY_PRODUCT_FIX_DETAIL + userId);

//				//发送短信
//				String userId=paramsMap.get("userId");
//				String cpType="";
//				String smsNo="sms04001";//config_sms表中参数
//				String tsje=paramsMap.get("turnOutAmount");
//				if (StringUtils.isBlank(userId) 
//						|| StringUtils.isBlank(smsNo)|| StringUtils.isBlank(tsje)) {
//					logger.debug("deposit/trunOut sendSMS 传入参数为空");
//				}
//				try{
//					// 发送短信
//					if(StringUtils.isEmpty(cpType)){
//						 sMSService.getSMS(userId,smsNo,tsje);	
//					}else{
//						sMSService.getSMS(userId,smsNo,tsje,cpType);	
//					}
//				} catch (Exception e) {
//					logger.error("deposit/trunOut sendSMS异常:" + e.getCause());
//				}
			}	
			CommonUtil.responseJson(result, response);
		} catch (Exception e) {
			logger.error("转出接口异常:" + com.edais.util.CommonUtil.printStackTraceToString(e));
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
				Consts.ERROR_CODE, "",
				Message.CnDescriptionExpression.BUSINESSE_ERROR);
			CommonUtil.responseJson(result, response);
		}
		System.out.println("deposit/trunOut接口\t执行耗时："+(System.currentTimeMillis()-a)/1000f+"秒");
		logger.debug("deposit/trunOut接口\t执行耗时："+(System.currentTimeMillis()-a)/1000f+"秒");
		logger.info("======方法执行结束：deposit/trunOut=======");
	}

	/**
	 * 转出接口数据检查
	 */
	private Map<String,Object> trunOutCheck(Map<String,String> paramMap) throws Exception{
		Map<String,Object> resMap = new HashMap<String,Object>();
		
		String finaceId = paramMap.get("finaceId");
		String userId = paramMap.get("userId");
		String turnOutAmount = paramMap.get("turnOutAmount");
		String passwordCash = paramMap.get("passwordCash");//交易密码
		
		if(StringUtils.isBlank(finaceId)){
			logger.error("转出接口数据检查失败：计划id为空");
			resMap.put("code", Consts.ERROR_CODE);
			resMap.put("message", Message.CnDescriptionExpression.BUSINESSE_ERROR);
			return resMap;
		}
		
		if(StringUtils.isBlank(userId)){
			logger.error("转出接口数据检查失败：用户id为空");
			resMap.put("code", Consts.ERROR_CODE);
			resMap.put("message", Message.CnDescriptionExpression.BUSINESSE_ERROR);
			return resMap;
		}
		
		if(StringUtils.isBlank(turnOutAmount)){
			logger.error("转出接口数据检查失败：转出金额为空");
			resMap.put("code", Consts.CHECK_CODE);
			resMap.put("message", Message.CnDescriptionExpression.AMOUNT_IS_NULL);
			return resMap;
		}
		
		if (StringUtils.isBlank(passwordCash)) {
			logger.error("转出接口数据检查失败：交易密码为空");
			resMap.put("code", Consts.CHECK_CODE);
			resMap.put("message", Message.CnDescriptionExpression.PAYPASSWORD_IS_NULL);
			return resMap;
		}
		
		// 转出金额检查
		boolean flag = turnOutAmount.matches("^[0-9]*[\\.]{0,1}[0-9]{0,2}$");
		if (!flag) {
			// 输入的值为非法字符
			resMap.put("code", Consts.CHECK_CODE);
			resMap.put("message",
					Message.CnDescriptionExpression.BUYAMOUNT_IS_NON_STANDARD);
			return resMap;
		}

		BigDecimal turnOutAmountBD = new BigDecimal(turnOutAmount);// 转出金额
		
		if(turnOutAmountBD.compareTo(BigDecimal.ZERO) == 0 || turnOutAmountBD.compareTo(BigDecimal.ZERO) == -1 ){
			// 输入的值为非法字符
			resMap.put("code", Consts.CHECK_CODE);
			resMap.put("message",
					Message.CnDescriptionExpression.BUYAMOUNT_IS_NON_STANDARD);
			return resMap;
		}
		
		//Modify by ZuoJun for turnout money in 2016-3-31 begin
		//后续流程重复获取在投金额和在投收益
		
		// 获取在投金额和在投收益
//		String result = depositService.findAccountAmount(paramMap);
//		JSONObject jsObj = JSONObject.parseObject(result);
//		String accountAmount = "0";
//		String currentIncome = "0";
//		if (jsObj != null && "00000".equals(jsObj.get("rescode"))) {
//			accountAmount = String.valueOf(jsObj.get("accountAmount"));
//			currentIncome = String.valueOf(jsObj.get("currentIncome"));
//		}
		
//		BigDecimal accountAmountAndIncome = new BigDecimal(accountAmount).add(new BigDecimal(currentIncome));
//		if (turnOutAmountBD.compareTo(accountAmountAndIncome) > 0) {
//			resMap.put("code", Consts.CHECK_CODE);
//			resMap.put("message","转出金额不能大于在投本金与在投收益之和("+accountAmountAndIncome+")!");
//			return resMap;
//		}
		
		//Modify by ZuoJun for turnout money in 2016-3-31 end
		
		// 判断提现支付密码是否正确
		User user = userService.getUserDetail(userId);
		if(!MD5.md5(passwordCash).equals(user.getPassword_cash())){
			logger.error("转出接口数据检查失败：交易密码错误");
			resMap.put("code", Consts.CHECK_CODE);
			resMap.put("message", Message.CnDescriptionExpression.WRONG_PAYPASSWORD);
			return resMap;
		}
		
		resMap.put("code", Consts.SUCCESS_CODE);
		resMap.put("message", Consts.SUCCESS_DESCRIBE);
		return resMap;
	}
	
	/** 
	 * 余额购买，且余额>=理财计划购买金额（CenterAction）
	 * @param request
	 * @return response
	 * @throws Exception
	 */
	@RequestMapping(value = "/join")
	public void join(HttpServletRequest request, HttpServletResponse response){
		Map<String, Object> jsonMap = new HashMap<String, Object>();

		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
		// 用户id
		String userId = paramsMap.get("userId");
		// 购买理财计划金额
		String buyAmount = paramsMap.get("buyAmount");
		// 购买资产包id
		String finaceId = paramsMap.get("finaceId");
		// 资金流转方式
		String cycleMatchType = paramsMap.get("cycleMatchType");
		// 邀请码
		String invitationCd = paramsMap.get("invitationCd");
		//String rateIds = paramsMap.get("rateIds");//加息券ID
		//代金券Id
		String voucherId = paramsMap.get("voucherId");
		//代金券额度
		String voucherMoney = "";
		String ip = CommonUtil.getClientIP(request);
		
		IpLogBean logBean = new IpLogBean();
		logBean.setIp(ip);
		logBean.setAction("余额购买");
		logBean.setUser(userId);
		logBean.setStatus(Consts.ERROR_CN);
		logBean.setDetail(userId+"在APP端进行了余额购买操作");
		
		Map resMap = new HashMap<String,Object>();
		
		try {
			Map<String,String> checkMap = joinCheck(paramsMap);
			if (null == checkMap
					|| !Consts.SUCCESS_CODE.equals(checkMap.get("code"))) {
				if(StringUtils.isNotBlank(ip)){
					IpLog.printIpLog(logBean);
				}
				String result = CommonUtil.setResultStringCn(
						new HashMap<String, Object>(), checkMap.get("code"),
						"", checkMap.get("message"));
				// 处理返回结果
				CommonUtil.responseJson(result, response);
				return;
			}
			if(!"".equalsIgnoreCase(checkMap.get("voucherMoney")) && null!=checkMap.get("voucherMoney")
					&& !"".equalsIgnoreCase(voucherId) 
					&& !"null".equalsIgnoreCase(checkMap.get("voucherMoney"))
					&& !"null".equalsIgnoreCase(voucherId)
					&& null!=voucherId){
				voucherMoney = checkMap.get("voucherMoney");
				
				BigDecimal decBuyAmount = new BigDecimal(buyAmount);// 购买金额
				//投资金额的上下限检查
				Map<String,Object> finance = centerService.getDepositGetDetail(finaceId);
				Object minInvestMoneyz =finance.get("INVESTMINAMOUNT");
				Object maxBuyerAmountz =finance.get("REMANAMOUNT");
				BigDecimal minInvestMoney = new BigDecimal(minInvestMoneyz.toString());//最小投资金额
				BigDecimal maxBuyerAmount = new BigDecimal(maxBuyerAmountz.toString());//投资最大金额
				
				if((null != minInvestMoney && CommonUtil.checkAmount(decBuyAmount, minInvestMoney) < 0) || 
					(decBuyAmount.compareTo(BigDecimal.valueOf(0.00))==0)){
					//最小投资金额
					logger.debug("购买铃铛宝时购买金额低于最小投资金额，购买金额:" + decBuyAmount);
					if(StringUtils.isNotBlank(ip)){
						IpLog.printIpLog(logBean);
					}
					String result = CommonUtil.setResultStringCn(
						new HashMap<String, Object>(), Consts.CHECK_CODE, "", Message.CnDescriptionExpression.BUYAMOUNT_BELOW_MINAMOUNT);
					CommonUtil.responseJson(result, response);
					return;
				}
				
				if(null != maxBuyerAmount && CommonUtil.checkAmount(decBuyAmount, maxBuyerAmount) > 0){
					//购买最大金额
					logger.debug("购买厚钱宝时购买金额高于购买最大金额，购买金额:" + decBuyAmount);
					if(StringUtils.isNotBlank(ip)){
						IpLog.printIpLog(logBean);
					}
					String result = CommonUtil.setResultStringCn(
						new HashMap<String, Object>(), Consts.CHECK_CODE, "", Message.CnDescriptionExpression.BUYAMOUNT_EXCEEDS_MAXAMOUNT);
					CommonUtil.responseJson(result, response);
					return;
				}
				
				// 获取该用户的余额
				Map<String, Object> pageMode = new HashMap<String, Object>();
				pageMode.put("userId", userId);

				String acctBalance = "0.00";// 余额
				resMap = centerService.getCusBalance(pageMode);
				if (resMap != null && "00000".equals(resMap.get("rescode"))) {
					acctBalance = resMap.get("ACCTBALANCE") + "";
				} else {
					logger.error("购买厚钱宝调用核心E300012失败:" + resMap.get("resmsg"));
					if(StringUtils.isNotBlank(ip)){
						IpLog.printIpLog(logBean);
					}
					String result = CommonUtil.setResultStringCn(
						new HashMap<String, Object>(), Consts.ERROR_CODE, "", Message.CnDescriptionExpression.BUSINESSE_ERROR);
					CommonUtil.responseJson(result, response);
					return;
				}

				// 余额检查
				if ("0.00".equals(acctBalance) || StringUtils.isBlank(acctBalance)) {
					logger.debug("购买铃铛宝时余额不足,余额为:" + acctBalance);
					if(StringUtils.isNotBlank(ip)){
						IpLog.printIpLog(logBean);
					}
					String result = CommonUtil.setResultStringCn(
						new HashMap<String, Object>(), Consts.CHECK_CODE, "", Message.CnDescriptionExpression.BALANCE_IS_NOT_SUFFICIENT);
					CommonUtil.responseJson(result, response);
					return;
				}

				BigDecimal decBalance = new BigDecimal(acctBalance);// 余额

				// 余额-理财计划金额 < 0
				if ((decBalance.add(new BigDecimal(voucherMoney))).compareTo(decBuyAmount) < 0) {
					logger.debug("购买厚钱宝时余额不足,余额差:" + (decBalance.subtract(decBuyAmount)));
					if(StringUtils.isNotBlank(ip)){
						IpLog.printIpLog(logBean);
					}
					String result = CommonUtil.setResultStringCn(
						new HashMap<String, Object>(), Consts.CHECK_CODE, "", Message.CnDescriptionExpression.BALANCE_IS_NOT_SUFFICIENT);
					CommonUtil.responseJson(result, response);
					return;
				}
				
				pageMode.put("financeId", finaceId);
				pageMode.put("userId", userId);
				pageMode.put("investmentAmount", buyAmount);
				pageMode.put("cycleMatchType", cycleMatchType);
				pageMode.put("buyMedia","2");
				pageMode.put("voucherMoney",voucherMoney);
				pageMode.put("voucherId",voucherId);
				
				Map retMap = centerService.dealBuyDepositGetByBalance(pageMode);
				if(retMap == null){
					if(StringUtils.isNotBlank(ip)){
						IpLog.printIpLog(logBean);
					}
					String result = CommonUtil.setResultStringCn(
						new HashMap<String, Object>(),Consts.ERROR_CODE, Consts.ErrorMsg.MSG00001,Message.CnDescriptionExpression.BUSINESSE_ERROR);
					// 处理返回结果
					CommonUtil.responseJson(result, response);
					return;
				}else{
					jsonMap.put("orderId", retMap.get("orderId"));
				}
				
				logBean.setStatus(Consts.SUCCESS_CN);
				if(StringUtils.isNotBlank(ip)){
					IpLog.printIpLog(logBean);
				}
				
				String result = CommonUtil.setResultStringCn(
					jsonMap,Consts.SUCCESS_CODE, Consts.SUCCESS_DESCRIBE, "");
				
				//ouyy 活期投资成功发送短信
				JSONObject jsonObject = JSONObject.parseObject(result);
//				if(Consts.SUCCESS_CODE.equals(jsonObject.getString("rescode"))){
//					//推送购买微信/短信接口
//					sendMeidaAndSMS(userId,paramsMap, finaceId, buyAmount);
//				}
				jkxyService.sendMeidaAndSMS(jsonObject.getString("rescode"), userId, paramsMap, finaceId, buyAmount);
				//发送个推消息----add by gongyanlan
//				String smsNo="sms02002";//投资,config_sms表中参数,
//				String mobile = captchaService.getMobileById(userId);//通过用户ID查询使用手机号
//				String[] smsParams={buyAmount,"",""};
//				Map<String,Object> map=new HashMap<String,Object>();
//				map.put("userId", userId);
//				map.put("mobile", mobile);
//				map.put("title", "投资通知");//标题
//				map.put("messageDetailTypeNew", "4");//1.订制商品个人消息，2.还款成功，3.充值，4.投资，5,提现
//				map.put("messageDetailResult", "0");//0.执行成功消息提示，1.执行失败提示
//				map.put("smsParams", smsParams);//消息模板里需要替换的变量
//				map.put("smsNo", smsNo);
//				sMSService.sendGetuiMSG(map);
				//异步活期生成协议
//				jkxyService.setHqJkxy(finaceId, userId, retMap);
		        String bidId = this.depositService.queryBidIdByFinaceId(finaceId);
		        String[] arrayStr={this.userService.getSystemSettingValue("ftpAgreementUrl"),
		        		this.userService.getSystemSettingValue("ftpAgreementUrl_two")};
		        String investAmount = retMap.get("investAmount").toString();
		        String orderId = retMap.get("orderId").toString();
		        String investDateStr=this.depositService.getInvestYearAndMon(orderId,bidId);
		        for (int j = 0; j < arrayStr.length; j++) {
		        	this.depositService.createAgreement(userId, new BigDecimal(retMap.get("investAmount").toString()), bidId, retMap.get("orderId").toString(),arrayStr[j],investDateStr);
		        }
		        
				// 处理返回结果
				CommonUtil.responseJson(result, response);
			}else{
				BigDecimal decBuyAmount = new BigDecimal(buyAmount);// 购买金额
				//投资金额的上下限检查
				Map<String,Object> finance = centerService.getDepositGetDetail(finaceId);
				Object minInvestMoneyz =finance.get("INVESTMINAMOUNT");
				Object maxBuyerAmountz =finance.get("REMANAMOUNT");
				BigDecimal minInvestMoney = new BigDecimal(minInvestMoneyz.toString());//最小投资金额
				BigDecimal maxBuyerAmount = new BigDecimal(maxBuyerAmountz.toString());//投资最大金额
				
				if((null != minInvestMoney && CommonUtil.checkAmount(decBuyAmount, minInvestMoney) < 0) || 
					(decBuyAmount.compareTo(BigDecimal.valueOf(0.00))==0)){
					//最小投资金额
					logger.debug("购买铃铛宝时购买金额低于最小投资金额，购买金额:" + decBuyAmount);
					if(StringUtils.isNotBlank(ip)){
						IpLog.printIpLog(logBean);
					}
					String result = CommonUtil.setResultStringCn(
						new HashMap<String, Object>(), Consts.CHECK_CODE, "", Message.CnDescriptionExpression.BUYAMOUNT_BELOW_MINAMOUNT);
					CommonUtil.responseJson(result, response);
					return;
				}
				if(null != maxBuyerAmount && CommonUtil.checkAmount(decBuyAmount, maxBuyerAmount) > 0){
					//购买最大金额
					logger.debug("购买厚钱宝时购买金额高于购买最大金额，购买金额:" + decBuyAmount);
					if(StringUtils.isNotBlank(ip)){
						IpLog.printIpLog(logBean);
					}
					String result = CommonUtil.setResultStringCn(
						new HashMap<String, Object>(), Consts.CHECK_CODE, "", Message.CnDescriptionExpression.BUYAMOUNT_EXCEEDS_MAXAMOUNT);
					CommonUtil.responseJson(result, response);
					return;
				}
				
				// 获取该用户的余额
				Map<String, Object> pageMode = new HashMap<String, Object>();
				pageMode.put("userId", userId);

				String acctBalance = "0.00";// 余额
				resMap = centerService.getCusBalance(pageMode);
				if (resMap != null && "00000".equals(resMap.get("rescode"))) {
					acctBalance = resMap.get("ACCTBALANCE") + "";
				} else {
					logger.error("购买厚钱宝调用核心E300012失败:" + resMap.get("resmsg"));
					if(StringUtils.isNotBlank(ip)){
						IpLog.printIpLog(logBean);
					}
					String result = CommonUtil.setResultStringCn(
						new HashMap<String, Object>(), Consts.ERROR_CODE, "", Message.CnDescriptionExpression.BUSINESSE_ERROR);
					CommonUtil.responseJson(result, response);
					return;
				}

				// 余额检查
				if ("0.00".equals(acctBalance) || StringUtils.isBlank(acctBalance)) {
					logger.debug("购买铃铛宝时余额不足,余额为:" + acctBalance);
					if(StringUtils.isNotBlank(ip)){
						IpLog.printIpLog(logBean);
					}
					String result = CommonUtil.setResultStringCn(
						new HashMap<String, Object>(), Consts.CHECK_CODE, "", Message.CnDescriptionExpression.BALANCE_IS_NOT_SUFFICIENT);
					CommonUtil.responseJson(result, response);
					return;
				}

				BigDecimal decBalance = new BigDecimal(acctBalance);// 余额

				// 余额-理财计划金额 < 0
				if (decBalance.compareTo(decBuyAmount) < 0) {
					logger.debug("购买厚钱宝时余额不足,余额差:" + (decBalance.subtract(decBuyAmount)));
					if(StringUtils.isNotBlank(ip)){
						IpLog.printIpLog(logBean);
					}
					String result = CommonUtil.setResultStringCn(
						new HashMap<String, Object>(), Consts.CHECK_CODE, "", Message.CnDescriptionExpression.BALANCE_IS_NOT_SUFFICIENT);
					CommonUtil.responseJson(result, response);
					return;
				}
				
				pageMode.put("financeId", finaceId);
				pageMode.put("userId", userId);
				pageMode.put("investmentAmount", buyAmount);
				pageMode.put("cycleMatchType", cycleMatchType);
				pageMode.put("buyMedia","2");
				pageMode.put("voucherMoney","");
				pageMode.put("voucherId","");
				
				Map retMap = centerService.dealBuyDepositGetByBalance(pageMode);
				if(retMap == null){
					if(StringUtils.isNotBlank(ip)){
						IpLog.printIpLog(logBean);
					}
					String result = CommonUtil.setResultStringCn(
						new HashMap<String, Object>(),Consts.ERROR_CODE, Consts.ErrorMsg.MSG00001,Message.CnDescriptionExpression.BUSINESSE_ERROR);
					// 处理返回结果
					CommonUtil.responseJson(result, response);
					return;
				}else{
					jsonMap.put("orderId", retMap.get("orderId"));
				}
				
				logBean.setStatus(Consts.SUCCESS_CN);
				if(StringUtils.isNotBlank(ip)){
					IpLog.printIpLog(logBean);
				}
				String result = CommonUtil.setResultStringCn(
					jsonMap,Consts.SUCCESS_CODE, Consts.SUCCESS_DESCRIBE, "");
				
				//ouyy 活期投资成功发送短信
				JSONObject jsonObject = JSONObject.parseObject(result);
//				if(Consts.SUCCESS_CODE.equals(jsonObject.getString("rescode"))){
//					//推送购买微信/短信接口
//					sendMeidaAndSMS(userId,paramsMap, finaceId, buyAmount);
//				}
				jkxyService.sendMeidaAndSMS(jsonObject.getString("rescode"), userId, paramsMap, finaceId, buyAmount);
				//发送个推消息----add by gongyanlan
//				String smsNo="sms02002";//投资,config_sms表中参数,
//				String mobile = captchaService.getMobileById(userId);//通过用户ID查询使用手机号
//				String[] smsParams={buyAmount,"",""};
//				Map<String,Object> map=new HashMap<String,Object>();
//				map.put("userId", userId);
//				map.put("mobile", mobile);
//				map.put("title", "投资通知");//标题
//				map.put("messageDetailTypeNew", "4");//1.订制商品个人消息，2.还款成功，3.充值，4.投资，5,提现
//				map.put("messageDetailResult", "0");//0.执行成功消息提示，1.执行失败提示
//				map.put("smsParams", smsParams);//消息模板里需要替换的变量
//				map.put("smsNo", smsNo);
//				sMSService.sendGetuiMSG(map);
		        String bidId = this.depositService.queryBidIdByFinaceId(finaceId);
		        String[] arrayStr={this.userService.getSystemSettingValue("ftpAgreementUrl"),
		        		this.userService.getSystemSettingValue("ftpAgreementUrl_two")};
		        String investDateStr=this.depositService.getInvestYearAndMon(retMap.get("orderId").toString(),bidId);
		        for (int j = 0; j < arrayStr.length; j++) {
		        	this.depositService.createAgreement(userId, new BigDecimal(String.valueOf(retMap.get("investAmount"))), bidId, retMap.get("orderId").toString(),arrayStr[j],investDateStr);
		        }
				
				//异步活期生成协议
//				jkxyService.setHqJkxy(finaceId, userId, retMap);
				
				
				// 处理返回结果
				CommonUtil.responseJson(result, response);
			}
		} catch (Exception e) {
			logger.error("deposit/join 异常:" + com.edais.util.CommonUtil.printStackTraceToString(e));
			if(StringUtils.isNotBlank(ip)){
				IpLog.printIpLog(logBean);
			}
			String result = CommonUtil.setResultStringCn(
				new HashMap<String, Object>(),Consts.ERROR_CODE, Consts.ErrorMsg.MSG00001,Message.CnDescriptionExpression.BUSINESSE_ERROR);
			// 处理返回结果
			CommonUtil.responseJson(result, response);
		}
	}
	
	/***
	 * 本地调试地址
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/sendMediaSmsTEST")
	public void sendMediaSmsTEST(HttpServletRequest request, HttpServletResponse response){
		Map<String,String> paramsMap = new HashMap<String,String>();
		try {
			sendMeidaAndSMS("28644858",paramsMap,"108","888");
			//发送个推消息----add by gongyanlan
//			String smsNo="sms02002";//投资,config_sms表中参数,
//			String mobile = captchaService.getMobileById("28644858");//通过用户ID查询使用手机号
//			String[] smsParams={"888","",""};
//			Map<String,Object> map=new HashMap<String,Object>();
//			map.put("userId", "28644858");
//			map.put("mobile", mobile);
//			map.put("title", "投资通知");//标题
//			map.put("messageDetailTypeNew", "4");//1.订制商品个人消息，2.还款成功，3.充值，4.投资，5,提现
//			map.put("messageDetailResult", "0");//0.执行成功消息提示，1.执行失败提示
//			map.put("smsParams", smsParams);//消息模板里需要替换的变量
//			map.put("smsNo", smsNo);
//			sMSService.sendGetuiMSG(map);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/***
	 * 生产调试地址
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/shengcanSendMediaSmsTEST")
	public void shengcanSendMediaSmsTEST(HttpServletRequest request, HttpServletResponse response){
		Map<String,String> paramsMap = new HashMap<String,String>();
		try {
			sendMeidaAndSMS("28645244",paramsMap,"108","0.01");
			//发送个推消息----add by gongyanlan
//			String smsNo="sms02002";//投资,config_sms表中参数,
//			String mobile = captchaService.getMobileById("28645244");//通过用户ID查询使用手机号
//			String[] smsParams={"0.01","",""};
//			Map<String,Object> map=new HashMap<String,Object>();
//			map.put("userId", "28645244");
//			map.put("mobile", mobile);
//			map.put("title", "投资通知");//标题
//			map.put("messageDetailTypeNew", "4");//1.订制商品个人消息，2.还款成功，3.充值，4.投资，5,提现
//			map.put("messageDetailResult", "0");//0.执行成功消息提示，1.执行失败提示
//			map.put("smsParams", smsParams);//消息模板里需要替换的变量
//			map.put("smsNo", smsNo);
//			sMSService.sendGetuiMSG(map);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 根据USERID发送短信/微信
	 * @param userId
	 */
	public void sendMeidaAndSMS(String userId,Map<String,String> paramsMap,String finaceId,String buyAmount) throws Exception{
		//封装用户ID
		WeixinMediaBinding mediaBinding = new WeixinMediaBinding();
		mediaBinding.setUserId(Integer.parseInt(userId));
		
		//先推送微信，微信成功不发短信，失败再发短信
		String mobile = captchaService.getMobileById(userId);//通过用户ID查询使用手机号
		String mediaUid = weixinBindingService.queryMediaUid(mediaBinding);//通过用户ID实体类查询微信标识
		
		//TODO 逻辑判断
		if(null == mediaUid || "null".equalsIgnoreCase(mediaUid) || "".equalsIgnoreCase(mediaUid)){
			logger.info("[推送短信息]因手机号："+mobile+"并未绑定微信");
			//发送短信
			String cpType="";
			String smsNo="sms02002";//config_sms表中参数
			String tsje=paramsMap.get("buyAmount");
			if (StringUtils.isBlank(userId) 
					|| StringUtils.isBlank(smsNo)|| StringUtils.isBlank(tsje)) {
				logger.debug("deposit/join sendSMS 传入参数为空");
			}
			try{
				// 发送短信
				if(StringUtils.isEmpty(cpType)){
					 sMSService.getSMS(userId,smsNo,tsje);	
				}else{
					sMSService.getSMS(userId,smsNo,tsje,cpType);	
				}
			} catch (Exception e) {
				logger.error("deposit/join sendSMS异常:" + e.getCause());
			}
		}else{
			Map<String,String> weixinTMap = new HashMap<String,String>();
			weixinTMap.put("mediaUid", mediaUid);//微信用户唯一标识 
			String currentShowName=loanService.queryBitShowNameCurrent();//活期
			weixinTMap.put("productInfo", currentShowName);//产品内容
			weixinTMap.put("number", buyAmount);//购买金额
			weixinTMap.put("functionScope", "buy");//购买金额
			
			boolean sendRusult = SendWeiXinUtil.sendWeiXin(weixinTMap);
			if(!sendRusult){
				logger.info("[微信推送失败][推送短信息]因手机号："+mobile+"并未绑定微信或者未关注联币钱包微信号");
				//发送短信
				String cpType="";
				String smsNo="sms02002";//config_sms表中参数
				String tsje=paramsMap.get("buyAmount");
				if (StringUtils.isBlank(userId) 
						|| StringUtils.isBlank(smsNo)|| StringUtils.isBlank(tsje)) {
					logger.debug("deposit/join sendSMS 传入参数为空");
				}
				try{
					// 发送短信
					if(StringUtils.isEmpty(cpType)){
						 sMSService.getSMS(userId,smsNo,tsje);	
					}else{
						sMSService.getSMS(userId,smsNo,tsje,cpType);	
					}
				} catch (Exception e) {
					logger.error("deposit/join sendSMS异常:" + e.getCause());
				}
			}else{
				logger.info("[微信推送]手机号："+mobile+"推送成功");
			}
		}
	}
	
	/**
	 * 余额购买活期数据检查
	 * @param paramsMap
	 * @return
	 * @throws Exception
	 */
	private Map<String,String> joinCheck(Map<String, String> paramsMap) throws Exception{
		Map<String, String> resMap = new HashMap<String,String>();
		// 用户id
		String userId = paramsMap.get("userId");
		// 购买理财计划金额
		String buyAmount = paramsMap.get("buyAmount");
		// 购买资产包id
		String finaceId = paramsMap.get("finaceId");
		// 资金流转方式
		String cycleMatchType = paramsMap.get("cycleMatchType");
		// 邀请码
		String invitationCd = paramsMap.get("invitationCd");
		// 交易密码
		String passwordCash = paramsMap.get("passwordCash");
		//代金券Id
		String voucherId =  paramsMap.get("voucherId");
		
		resMap.put("voucherMoney","");
		// 用户id
		if (StringUtils.isBlank(userId)) {
			logger.error("余额购买活期数据检查失败： 用户id为空");
			resMap.put("code", Consts.ERROR_CODE);
			resMap.put("message", Message.CnDescriptionExpression.BUSINESSE_ERROR);
			return resMap;
		}
		
		// 购买资产包id
		if (StringUtils.isBlank(finaceId)) {
			logger.error("余额购买活期数据检查失败： 购买资产包id为空");
			resMap.put("code", Consts.ERROR_CODE);
			resMap.put("message", Message.CnDescriptionExpression.BUSINESSE_ERROR);
			return resMap;
		}
		//资金流转方式
		if (StringUtils.isBlank(cycleMatchType)) {
			logger.error("余额购买活期数据检查失败： 资金流转方式为空");
			resMap.put("code", Consts.ERROR_CODE);
			resMap.put("message", Message.CnDescriptionExpression.BUSINESSE_ERROR);
			return resMap;
		}

		// 购买金额检查（必须是100元以上,且小数点后2位）
		boolean flag = buyAmount.matches("^[0-9]*[\\.]{0,1}[0-9]{0,2}$");
		if (!flag) {
			logger.debug("购买鼓钱包时输入的购买金额非法，购买金额:" + buyAmount);
			// 输入的值为非法字符
			resMap.put("code", Consts.CHECK_CODE);
			resMap.put("message", Message.CnDescriptionExpression.BUYAMOUNT_IS_NON_STANDARD);
			return resMap;
		}
		// 购买份数
		if (StringUtils.isBlank(buyAmount) || Double.valueOf(buyAmount) < 100) {
			logger.error("余额购买活期数据检查失败： 购买金额是:" + buyAmount);
			resMap.put("code", Consts.CHECK_CODE);
			resMap.put("message", Message.CnDescriptionExpression.AMOUNT_IS_NULL);
			return resMap;
		}
		
		// 开关控制最大金额 by ouyy
		String kgValue=userService.getSystemSettingValue("hq_gmzded_kg_value");//优享计划-购买最大额度-开关 0-表示关　1-表示开
		if("1".equals(kgValue)){
			String maxBuyerAmountz=userService.getSystemSettingValue("hq_gmzded_value");
			Map<String,String> reOrMap=new HashMap<String,String>();
			reOrMap.put("type", "109");
			reOrMap.put("userId", userId);
			String investAmount=orderService.getOrderInvestAmount(reOrMap);
			BigDecimal maxBuyerAmount = new BigDecimal((null==maxBuyerAmountz||"".equals(maxBuyerAmountz))?"0":maxBuyerAmountz);//投资最大金额
			BigDecimal buyAmountBig=new BigDecimal(buyAmount).add(new BigDecimal(investAmount));//购买金额加订单金额
			logger.info("允许购买活期总额:"+maxBuyerAmountz);
			logger.info("活期购买金额:"+buyAmount);
			logger.info("活期订单购买总额:"+investAmount);
			if(CommonUtil.checkAmount(buyAmountBig, maxBuyerAmount) > 0){
				//购买最大金额
				logger.info("亲爱的用户，您的活期账户投资金额不能超过"+maxBuyerAmountz+"元");
				resMap.put("code", Consts.CHECK_CODE);
				resMap.put("message", "亲爱的用户，您的活期账户投资金额不能超过"+maxBuyerAmountz+"元");
				return resMap;
			}
		}

		// 交易密码验证
		if (StringUtils.isBlank(passwordCash)) {
			logger.error("余额购买活期数据检查失败：交易密码为空");
			resMap.put("code", Consts.ERROR_CODE);
			resMap.put("message", "交易密码不能为空!");
			return resMap;
		}

		try {
			User user = userService.getUserDetail(userId);
			String passwordMd5 = MD5.md5(passwordCash);
			if (!passwordMd5.equals(user.getPassword_cash())) {
				resMap.put("code", Consts.ERROR_CODE);
				resMap.put("message", "交易密码错误，请重新输入！");
				return resMap;
			}
		} catch (Exception e) {
			resMap.put("code", Consts.ERROR_CODE);
			resMap.put("message", Message.CnDescriptionExpression.BUSINESSE_ERROR);
			return resMap;
		}
		
		/** 获取用户是否实名认证,对于实名认证用户取得身份证号和姓名 */
		User user = userService.getUserDetail(userId);
		// 判断用户是否实名认证
		if (!"1".equals(user.getIs_create_acct()) || !"Y".equals(user.getIdcard_validate())) {
			logger.error("余额购买活期数据检查失败：用户没有经过实名认证");
			// 没有经过实名认证不能进行购买
			resMap.put("code", Consts.CHECK_CODE);
			resMap.put("message", Message.CnDescriptionExpression.AUTHENTICATION_IS_NOT);
			return resMap;
		}
		
		/** 获取购买的产品是否在预售期内 */
		String checkResult = centerService.checkdepositGetSellTime(finaceId);
		if (!"true".equals(checkResult)) {
			logger.debug("deposit/join 购买活动未开始或者已结束");
			String msgCn;
			if("buy.has.not.started".equals(checkResult)){
				msgCn = Message.CnDescriptionExpression.BUY_HAS_NOT_STARTED;
			}else if("buy.has.ended".equals(checkResult)){
				msgCn = Message.CnDescriptionExpression.BUY_HAS_ENDED;
			}else{
				msgCn = Message.CnDescriptionExpression.PLAN_HAS_NOT_OPENED;
			}
			resMap.put("code", Consts.CHECK_CODE);
			resMap.put("message", msgCn);
			return resMap;
		}
		
		
		if(null==voucherId || "".equalsIgnoreCase(voucherId) || "null".equalsIgnoreCase(voucherId)){
			voucherId ="";
		}else{
			Map<String,Object> reqMap = new HashMap<String,Object>();
			reqMap.put("voucherId", voucherId);
			Map<String, Object> voucherMap = new HashMap<String, Object>();
			voucherMap = this.userVouchersService.queryUserVochersById(reqMap);
			if(Consts.ERROR_CODE.equalsIgnoreCase(String.valueOf(voucherMap.get("rescode")))){
				logger.error("该代金券不存在！");
				// 该代金券不存在！
				resMap.put("code", Consts.CHECK_CODE);
				resMap.put("message", "该代金券不存在！");
				return resMap;
			}else{
				if(Consts.SUCCESS_CODE.equalsIgnoreCase(String.valueOf(voucherMap.get("rescode")))){
					UserVouchers  userVouchers = (UserVouchers)voucherMap.get("userVouchers");
					//根据代金券Id库存代金券信息
					Map<String, Object> voucherMap2 = new HashMap<String, Object>();
					voucherMap2 = this.userVouchersService.queryVochersInfoById(String.valueOf(userVouchers.getVoucher_type_id()));
					if(Consts.ERROR_CODE.equalsIgnoreCase(String.valueOf(voucherMap2.get("rescode")))){
						logger.error("该活期代金券库存不足异常");
						// 库存不足代金券异常
						resMap.put("code", Consts.CHECK_CODE);
						resMap.put("message", "该活期代金券库存不足异常");
						return resMap;
					}
					if(new BigDecimal(buyAmount).compareTo(userVouchers.getInvestment_amount())<0){
						logger.error("您输入的金额未满足使用代金券规则");
						// 库存不足代金券异常
						resMap.put("code", Consts.CHECK_CODE);
						resMap.put("message", "您输入的金额未满足使用代金券规则");
						return resMap;
					}
					
					VouchersRule vouchersRule = (VouchersRule)voucherMap2.get("vouchersRule");
					if(userVouchers.getInvestment_amount().compareTo(vouchersRule.getInvestment_amount())!=0){
						logger.error("您的这张代金券有问题，请联系客服");
						// 库存不足代金券异常
						resMap.put("code", Consts.CHECK_CODE);
						resMap.put("message", "代金券使用出现异常，请联系客服");
						return resMap;
		 			}
					
					if(userVouchers.getVoucher_amount().compareTo(vouchersRule.getVoucher_amount())!=0){
						logger.error("您的这张代金券有问题，请联系客服");
						// 库存不足代金券异常
						resMap.put("code", Consts.CHECK_CODE);
						resMap.put("message", "代金券使用出现异常，请联系客服");
						return resMap;
		 			}
					
					Map<String, String> resMap2 = new HashMap<String,String>();
					resMap2.put("voucherMoney", String.valueOf(vouchersRule.getVoucher_amount()));
					resMap2.put("code", Consts.SUCCESS_CODE);
					resMap2.put("message", Consts.SUCCESS_DESCRIBE);
					return resMap2;
				}
			}
		}
		resMap.put("code", Consts.SUCCESS_CODE);
		resMap.put("message", Consts.SUCCESS_DESCRIBE);
		return resMap;

	}
	
	/**
	 * 获取我的账户详情
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/queryMyAccountDetail")
	//@RequestMapping(value = "/queryMyAccountDetail",method=RequestMethod.GET)
	public void queryMyAccountDetail(HttpServletRequest request,
			HttpServletResponse response) throws Exception{
		if (!RequestUtil.validSign(request)) {
			logger.info("无效签名");
			ResponseUtil.write(response, ResultConstant.INVALID_SIGN);
			return;
		}
		if (!RequestUtil.validToken(request)) {
			logger.info("无效token");
			ResponseUtil.write(response, ResultConstant.INVALID_TOKEN);
			return;
		}
		RequestHeader header = RequestUtil.decodeHeader(request);
		// 用户id
		String userId = String.valueOf(header.getUserId());
		Map<String, String> paramsMap = new HashMap<String, String>();
		paramsMap.put("userId",userId);
		String result = null;
//		JSONObject newJsonObject = new JSONObject();
//		Map<String, Object> jsonMap = new HashMap<String, Object>();
		//我的资产
		result = depositService.queryMyAccountDetail(paramsMap);
		JSONObject jsonObject = JSONObject.parseObject(result);
		String accountDetail = jsonObject.getString("accountDetail");
		JSONObject accountDetailObject = JSONObject.parseObject(accountDetail);
		String passwordCash=accountDetailObject.getString("passwordCash");
		accountDetailObject.put("isSetTradePWD",StringUtil.isNotEmpty(passwordCash)?"Y":"N");
		paramsMap.put("finaceId", "1");
		//app活期理财
		/**String fundDetailResult = depositService.queryMoneyFundDetail(paramsMap);
		JSONObject fundDetailObject = JSONObject.parseObject(fundDetailResult);
		String currentAmount = fundDetailObject.getString("accountAmount");
		String currentIncome = fundDetailObject.getString("currentIncome");

		jsonMap = this.assetsService.getAssets(userId);          //微信我的资产总览

		String totalAssets = jsonMap.get("totalAssets").toString();            //账户总资产
		String incomeAmount = jsonMap.get("incomeAmount").toString();           //账户累计收益
		String expectAmount = jsonMap.get("expectAmount").toString();	//定期预计收益
		String yesterdayGain = fundDetailObject.get("yesterdayGain").toString(); //昨日收益  */

		Map<String,Object> reqMap = new HashMap<String,Object>();
		reqMap.put("status", "0");
		reqMap.put("userId", userId);
		Integer rateRisesTotalNum = this.rateRisesCouponsService.queryRateRisesCouponsListByParamsCount(reqMap);
		Integer vouchersTotalNum = this.userVouchersService.queryVouchersByUserAllCount(reqMap);
		Map<String,Object> userMobileMap = this.userService.getUserMobile(userId);
//		String giftBalance = String.valueOf(accountDetailObject.get("giftBalance"));
//		DecimalFormat df = new DecimalFormat("#.00");
		/**
		//账户总资产
		accountDetailObject.put("totalAssets", df.format(new BigDecimal(totalAssets).add(new BigDecimal(giftBalance))));
		//账户累计收益
		accountDetailObject.put("incomeAmount", incomeAmount);
		//活期在投资产
		BigDecimal currentSum = new BigDecimal(currentAmount).add(new BigDecimal(currentIncome));
		accountDetailObject.put("currentAmount", currentSum);
		//活期在投收益
		accountDetailObject.put("currentIncome", currentIncome);
		//定期预计收益
		accountDetailObject.put("expectAmount", expectAmount);
		//活期昨日收益
		accountDetailObject.put("yesterdayGain", yesterdayGain);*/
		//用户ID
		accountDetailObject.put("userId", userId);
		//用户手机号-隐藏中间四位
		String mobile = String.valueOf(userMobileMap.get("mobile"));
		if(StringUtil.isNotEmpty(mobile)){
			mobile = mobile.substring(0,3) + "****" + mobile.substring(7, mobile.length());
		}
		accountDetailObject.put("mobile", userMobileMap.get("mobile"));

		//加息券数量
		accountDetailObject.put("rateRisesTotalNum", rateRisesTotalNum);
		accountDetailObject.put("vouchersTotalNum", vouchersTotalNum);
		//是否绑卡
		List<UserRecePayCard> cardList = this.userCardService.queryUserCardListInfoByUserId(reqMap);
		String isBindingCard = "N";
		if(cardList!=null && cardList.size()> 0){
			isBindingCard = "Y";
		}
		accountDetailObject.put("isBindingCard", isBindingCard);

		/**用户是否完成任务 （0：未完成	，1：已完成）*/

		//获取活期利率
		/**BigDecimal adjustRate=new BigDecimal(fundDetailObject.get("adjustRate").toString());
		//获取签到加息
		BigDecimal signInRateRises=new BigDecimal(fundDetailObject.get("signInRateRises").toString());
		//获取当日加息利率
		BigDecimal couponsRateRises=new BigDecimal(fundDetailObject.get("couponsRateRises").toString());*/

		//总加息
		/**BigDecimal totalRate=signInRateRises.add(couponsRateRises).add(adjustRate);*/
		//查询用户最高收益值上限
		/**float userMaxRaise=Float.valueOf(rateRisesCouponsService.findParamValueByName("user_max_raise"));
		String isCompleteTask="0";
		if(totalRate.floatValue()>=userMaxRaise){
			isCompleteTask="1";
		}
		accountDetailObject.put("isCompleteTask", isCompleteTask);*/

//			/** 将数据同步到Redis **/
//			RedisOperateUtil.setString(RedisContant.KEY_MY_ASSET_PAGE + userId, accountDetailObject.toString());

		//增加优享计划，抵用券数量，优享金额，昨日收益 by fanping
		try {
			Map<String, String> enjoyMap =enjoyService.getEnjoyByNumAmIc(userId);
			if(enjoyMap!=null&&enjoyMap.size()!=0){
				accountDetailObject.put("curHelpNub", (String)enjoyMap.get("curHelpNub"));
				accountDetailObject.put("enjoyPlanAmount",StringUtil.isEmpty(enjoyMap.get("enjoyPlanAmount"))==true?"0":enjoyMap.get("enjoyPlanAmount"));
				accountDetailObject.put("enjoyYesterdayIncome",StringUtil.isEmpty(enjoyMap.get("enjoyYesterdayIncome"))==true?"0":enjoyMap.get("enjoyYesterdayIncome"));
				accountDetailObject.put("isValidYxjh", (String)enjoyMap.get("ISVALIDYXJH"));
				accountDetailObject.put("isValidDq",(String) enjoyMap.get("ISVALIDDQ"));
				accountDetailObject.put("isValidHq",(String) enjoyMap.get("ISVALIDHQ"));
			}else{
				accountDetailObject.put("curHelpNub", "0");
				accountDetailObject.put("enjoyPlanAmount","0");
				accountDetailObject.put("enjoyYesterdayIncome","0");
				accountDetailObject.put("isValidYxjh", "Y");
				accountDetailObject.put("isValidDq","Y");
				accountDetailObject.put("isValidHq","Y");
			}
			//理财总资产
			String currInvestAmount=enjoyMap.get("enjoyPlanAmount");
			accountDetailObject.put("currInvestAmount",currInvestAmount);
			//账户余额
			String acctBalance=String.valueOf(accountDetailObject.get("acctBalance"));
			//账户总资产 = 理财总资产 + 账户余额
			DecimalFormat df = new DecimalFormat("#0.00");
			accountDetailObject.put("totalAssets", df.format(new BigDecimal(currInvestAmount).add(new BigDecimal(acctBalance))));
			//帮助页地址
			String helpURL = this.userService.getSystemSettingValue("helpURL");
			accountDetailObject.put("helpURL", helpURL);
			/*判断版本号小于2.8不显示*/
			String version=paramsMap.get("version");
			if(null!=version&&!"".equals(version.trim())){
				version=version.replaceAll("\\.", "");
				if(Double.parseDouble(version)!=100){
					if(Double.parseDouble(version)<=280){
						accountDetailObject.put("isValidYxjh", "N");
					}
				}
			}else{
				accountDetailObject.put("isValidYxjh", "N"); //如果为空，表示APP是以前的版本，开关置为关闭状态
			}
		} catch (Exception e) {
			accountDetailObject.put("curHelpNub", "0");
			accountDetailObject.put("enjoyPlanAmount","0");
			accountDetailObject.put("enjoyYesterdayIncome","0");
			accountDetailObject.put("isValidYxjh", "Y");
			accountDetailObject.put("isValidDq","Y");
			accountDetailObject.put("isValidHq","Y");

			logger.error("查询优享计划资产接口发生异常",e);
		}


		try {
			//查询用户是否为销售人员
			Map<String,Object> memberMap=new HashMap<String,Object>();
			memberMap.put("salemanMobile",String.valueOf(userMobileMap.get("mobile")));
			List<Map<String, Object>> memberInfoList=kcodeChannelService.queryMemberInfoList(memberMap);
			if(memberInfoList!=null&&memberInfoList.size()>0){
				accountDetailObject.put("isSaleMan","Y");
			}else{
				accountDetailObject.put("isSaleMan","N");
			}
		} catch (Exception e) {
			accountDetailObject.put("isSaleMan","N");
			logger.error("查询用户是否为销售人员发生异常",e);
		}

		try {//风险评估 add by gaojing
			RiskEvaluation riskEvaluation=riskEvaluationService.getRiskEvaluationByUserId(userId);
			accountDetailObject.put("isRiskEvaluation",riskEvaluation.getIsRisk());
			accountDetailObject.put("riskType",riskEvaluation.getRiskType());
		} catch (Exception e) {
			accountDetailObject.put("isRiskEvaluation","N");
			logger.error("查询风险评估异常",e);
		}

		/**
            try {
                //查询积分和积分开关 +积分 等级
                String phone = userMobileMap.get("mobile").toString();
                JSONObject  jb= pointService.getPoint(userId,phone);
                logger.info("查询用户积分以及积分开关调用shop系统,shop系统返回"+jb.toString());
                String usablePoint=jb.getString("usablePoint");//用户当前可用积分
                String pointSwitch=jb.getString("pointSwitch");//积分开关
                String pointGrade=jb.getString("pointGrade");//积分等级
                String gradeName=jb.getString("gradeName");//积分等级名称
                accountDetailObject.put("pointSwitch",pointSwitch);
                accountDetailObject.put("usablePoint",usablePoint);
                accountDetailObject.put("pointGrade",pointGrade);
                accountDetailObject.put("gradeName",gradeName);

            } catch (Exception e) {
                accountDetailObject.put("pointSwitch","Y");
                accountDetailObject.put("usablePoint","0");
                accountDetailObject.put("pointGrade","1");
                logger.error("查询用户积分以及积分开关异常",e);
            }
            */
		/**
		try {
			//查询一元购开关  wdq
			Map<String,Object> yygMap = new HashMap<String,Object>();
			yygMap.put("userId", userId);
			String yygkg = systemSettingService.getSystemSettingValueByName("yygkgzh");
			logger.info("查询一元购开关状态"+yygkg);
			int yygVoucherAcount = shopVouchersService.shopVochersCount(yygMap);
			accountDetailObject.put("yygVoucherAcount",String.valueOf(yygVoucherAcount));
			if("1".equals(yygkg)) {
				accountDetailObject.put("isValidYygKg","Y");
			} else {
				accountDetailObject.put("isValidYygKg","N");
			}
		} catch (Exception e) {
			accountDetailObject.put("isValidYygKg","N");
			accountDetailObject.put("yygVoucherAcount","0");
			logger.error("查询一元购开关异常",e);
		}
		*/

		try {
			//礼包数量+礼包开关 +礼包金额
			String giftPackageSwitch="Y";//礼包开关 默认开
			  String giftPackageSum="0";//礼包的数量 默认是0（状态为0的礼包订单数量和）
			//礼包的金额 加在核心sqlmyAccountDetailSql.xml  字段名称giftBalance

			String phone = String.valueOf(userMobileMap.get("mobile"));
			JSONObject jb=giftPackageOrderService.giftPackageJoinMyAccount(userId, phone);

			giftPackageSwitch=jb.getString("giftPackageSwitch");
			giftPackageSum=jb.getString("giftPackageSum");

			accountDetailObject.put("giftPackageSwitch",giftPackageSwitch);
			accountDetailObject.put("giftPackageSum",giftPackageSum);


		} catch (Exception e) {
			accountDetailObject.put("giftPackageSwitch","Y");
			accountDetailObject.put("giftPackageSum","0");
			logger.error("查询礼包异常",e);
			e.printStackTrace();
		}
		ResultDTO resultDTO = new ResultDTO(ResultCode.SUCCESS.getCode(),ResultCode.SUCCESS.getMsg(),
				ResultCode.SUCCESS.getType(),accountDetailObject);
		ResponseUtil.write(response,  resultDTO);
	}
	
	/**
	 * 美恰对接查询用户账户和信息
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/queryUserInfoAndAcctInfo")
	public void queryUserInfoAndAcctInfo(HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();

		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
		// 用户id
		String mobile = paramsMap.get("mobile");
		
		if (StringUtils.isBlank(mobile)) {
			logger.error("美恰对接查询用户账户和信息检查失败：手机号为空");
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
				Consts.ERROR_CODE, "",Message.CnDescriptionExpression.BUSINESSE_ERROR);
			// 处理返回结果
			CommonUtil.responseJson(result, response);
			return;
		}
		
		try{
			Map<String,Object> reqeustMap = new HashMap<String,Object>();
			reqeustMap.put("mobile", mobile);
			//根据手机号查询用户信息
			User user = this.userService.getUserByParm(reqeustMap);
			
			String result = "";
			if(user!=null){
				paramsMap.put("userId",String.valueOf(user.getId()));
				String resultStr = depositService.queryMyAccountDetail(paramsMap);
				JSONObject jsonObject = JSONObject.parseObject(resultStr);
				String accountDetail = jsonObject.getString("accountDetail");
				JSONObject accountDetailObject = JSONObject.parseObject(accountDetail);
				
				Map<String,Object> resultMap = this.assetsService.getAssets(String.valueOf(user.getId()));   
				 
				//活期资产
				paramsMap.put("finaceId", "1");
				//app活期理财
				String fundDetailResult = depositService.queryMoneyFundDetail(paramsMap);
				JSONObject fundDetailObject = JSONObject.parseObject(fundDetailResult);  
				String currentAmount = fundDetailObject.getString("accountAmount");
				String currentIncome = fundDetailObject.getString("currentIncome");
				
				//活期在投资产
				BigDecimal currentSum = new BigDecimal(currentAmount).add(new BigDecimal(currentIncome));
				
				//定期资产
				String investAmountSum = accountDetailObject.getString("investAmountSum");
				
				//用户是否实名					【姓】：已实名 【X】：未实名
				String userNameInfo = "";
				if(user.getIdcard_validate().equals("Y")){
					UserInfo userInfo = this.userService.getUserInfo(String.valueOf(user.getId()));
					userNameInfo = userInfo.getReal_name().substring(0,1);
				}else{
					userNameInfo = "X";
				}
				 
				
				//是否有活期理财
				boolean existOrderId = this.userService.isExistOrderInfo(String.valueOf(user.getId()));
				String demandOrderInfo = "";
				if(existOrderId){
					String incomeTotal = fundDetailObject.getString("incomeTotal");
					BigDecimal incomeSum = new BigDecimal(incomeTotal);
					
					if(incomeSum.compareTo(new BigDecimal(5000))>=0){
						demandOrderInfo = "1";
					}else if(incomeSum.compareTo(new BigDecimal(2000))>=0){
						demandOrderInfo = "2";
					}else if(incomeSum.compareTo(new BigDecimal(1000))>=0){
						demandOrderInfo = "3";
					}else if(incomeSum.compareTo(new BigDecimal(100))>=0){
						demandOrderInfo = "4";
					}else{
						demandOrderInfo = "5";
					}
					
//					jsonMap.put("incomeSum", incomeSum.toString());

				}else{
					demandOrderInfo = "0";
				}
				
				//是否有路由器理财
				reqeustMap.put("mobile", mobile);
				
				List<UserLDActivityInfo> activityInfoByMbList = activityService.findActivityInfoByParm(reqeustMap);
				String isExistLDOrder = "";
				String notInOrder = "";
				if(activityInfoByMbList!=null && activityInfoByMbList.size()>0){
					isExistLDOrder = "1";
					for (UserLDActivityInfo info : activityInfoByMbList) {
						notInOrder = notInOrder + info.getStep1_order_id() + ",";
					}
					notInOrder = notInOrder.substring(0,notInOrder.length() -1);
				}else{
					isExistLDOrder = "2";
				}
				
				//是否存在定期理财
				reqeustMap.put("currentPage", 1);
				reqeustMap.put("pageSize", 20000);
				reqeustMap.put("type", "2");
				reqeustMap.put("userId",String.valueOf(user.getId()));
				
				reqeustMap.put("notInOrder", notInOrder);
				reqeustMap.put("productType", "108");
				reqeustMap.put("isAddOverFlg", "1");
				
				List<OrderListVo> orderList = orderService.queryOrderList(reqeustMap);
				BigDecimal regularSum = BigDecimal.ZERO;
				for(OrderListVo order :orderList){
					if(StringUtils.isNotBlank(order.getInvestAmount())){
						regularSum = regularSum.add(new BigDecimal(order.getInvestAmount()));
					}
				}
				
//				jsonMap.put("regularSum", regularSum);
				String regularOrderInfo = "";
				if(orderList.size()>0){
					if(regularSum.compareTo(new BigDecimal(200000))>=0){
						regularOrderInfo = "1";
					}else if(regularSum.compareTo(new BigDecimal(100000))>=0){
						regularOrderInfo = "2";
					}else if(regularSum.compareTo(new BigDecimal(50000))>=0){
						regularOrderInfo = "3";
					}else if(regularSum.compareTo(new BigDecimal(10000))>=0){
						regularOrderInfo = "4";
					}else{
						regularOrderInfo = "5";
					}
				}else{
					regularOrderInfo = "0";
				}
				
				jsonMap.put("mobile", mobile);
				jsonMap.put("userNameInfo", userNameInfo);
				jsonMap.put("demandOrderInfo", demandOrderInfo);
				jsonMap.put("regularOrderInfo", regularOrderInfo);
				jsonMap.put("isExistLDOrder", isExistLDOrder);
				
				result = CommonUtil.setResultStringCn(jsonMap,
						Consts.SUCCESS_CODE, Consts.SUCCESS_DESCRIBE,"");                            
			}else{
				jsonMap.put("mobile", mobile);
				
				result = CommonUtil.setResultStringCn(jsonMap,
						Consts.SESSION_LOSE_CODE,"faild" ,Consts.ErrorMsg.MSG00021);
			}
			
			CommonUtil.responseJson(result, response);
		}catch (Exception e) {
			logger.error("美恰对接查询用户账户和信息异常:" + com.edais.util.CommonUtil.printStackTraceToString(e));
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
				Consts.ERROR_CODE, "",
				Message.CnDescriptionExpression.BUSINESSE_ERROR);
			CommonUtil.responseJson(result, response);
		}
		
		
		
	}
	
	/**
	 * 进行风险承受能力评估
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/queryRiskEvaluation")
	public void queryRiskEvaluation(HttpServletRequest request, HttpServletResponse response)throws Exception {

		if (!RequestUtil.validSign(request)) {
			logger.info("无效签名");
			ResponseUtil.write(response, ResultConstant.INVALID_SIGN);
			return;
		}
		if (!RequestUtil.validToken(request)) {
			logger.info("无效token");
			ResponseUtil.write(response, ResultConstant.INVALID_TOKEN);
			return;
		}
		RequestHeader header = RequestUtil.decodeHeader(request); // 解密header
		Map<String,Object> 	paramsMap = RequestUtil.decodeData(request); // 解密请求参数

		Map<String, Object> rtnMap = new HashMap<String, Object>();
		String answer = String.valueOf(paramsMap.get("answer"));
		if (StringUtils.isBlank(answer)) {
			logger.error("风险评估失败：用户用户答案为空" );
			ResponseUtil.write(response,new ResultDTO(ResultCode.FAILED,"answer不能为空！"));
		}

		Map<String, String> paraMap = new HashMap<String, String>();
		paraMap.put("userId",header.userId2String());
		paraMap.put("answer", answer);
		rtnMap = riskEvaluationService.queryRiskEvaluation(paraMap);
		// 处理返回结果
		ResultDTO<Map> resultDTO = new ResultDTO<>(ResultCode.SUCCESS);
		resultDTO.setRecord(rtnMap);
		ResponseUtil.write(response,  resultDTO);
		
	}
	
	
	/**
	 * 获取是否风险评估
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/getRiskEvaluationById")
	public void getRiskEvaluationById(HttpServletRequest request, HttpServletResponse response)throws Exception{
		logger.info("==========获取是否风险评估接口 start");

		if (!RequestUtil.validSign(request)) {
			logger.info("无效签名");
			ResponseUtil.write(response, ResultConstant.INVALID_SIGN);
			return;
		}
		if (!RequestUtil.validToken(request)) {
			logger.info("无效token");
			ResponseUtil.write(response, ResultConstant.INVALID_TOKEN);
			return;
		}

		RequestHeader header = RequestUtil.decodeHeader(request);
		Map<String, Object> rtnMap = new HashMap<String, Object>();

		RiskEvaluation riskEvaluation = riskEvaluationService.getRiskEvaluationByUserId(String.valueOf(header.getUserId()));
		rtnMap.put("isRiskEvaluation", riskEvaluation.getIsRisk());
		rtnMap.put("riskType", riskEvaluation.getRiskType());
		rtnMap.put("mark", riskEvaluation.getMark());
		rtnMap.put("declare", riskEvaluation.getDeclare());

		// 处理返回结果
		ResultDTO<Map> resultDTO = new ResultDTO<>(ResultCode.SUCCESS);
		resultDTO.setRecord(rtnMap);
		ResponseUtil.write(response,  resultDTO);
	
	}
	
}
